PyCharm is showing me that some code is unreachable within a method before the return statement is reached. I cannot help but wonder how is that even remotely possible?
def post(self):
# get the desired parameters
username = self.request.get('user')
password = self.request.get('pass')
if not self.REGEX.match(username) or not self.REGEX.match(password):
logging.debug('RegistrationHandler: Bad credentials ->', username, password)
self.fail('bad username or password')
print 'Blah' # <---- shows as UNREACHABLE ?
return # <---- shows as UNREACHABLE ?
self.fail simply calls self.response.write(things).
Update:
Yeah, when I surround it with a try/catch clause, the issue is resolved... Strange. (Note that the method doesn't always raise an exception.
I actually think this is a bug in PyCharm, thinking that fail refers to TestCase.fail, which would in fact make the code unreachable.
If I use your example, but rename fail to for example failure, the errors disappears. I'd report this bug to the friendly folks at PyCharm to see if this is in fact the case.
This code is unreachable less...
Inspection info: This inspection detects code which can not be normally reached.
import random
from typing import List, Any
while True:
x: List[Any] = list(str(random.sample(range(1001, 10000), 1)))
x.remove("[")
x.remove("]")
print(x)
check the indentation of your function and the statement/line which is unreachable.
I used it like the second function is included in the first functions' indentation
How the code should be when indentation removed
then I removed the indentation before if statement and I got the result.
.
.
.
.
.
.
.
.
You are Welcome!
Related
We are willing/ forced to develop a small Web App for the university. Now we started and everything seems to be fine, until the above strange error raises.
Statement expected, found py: Dedent
The error is raised by the following lines of code:
def get_reset_token(self, mysql, userid):
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.execute("""SELECT token FROM tralala_reset_password
WHERE uid=(%s)""", userid)
data = cursor.fetchall()
cursor.close()
conn.close()
return data[0]
except Exception as e:
app.logger(str(e))
return ""
PyCharm started to mark the return "" statement.
If you face this issue in PyCharm 2021.2 add the following line
-ea
to Help | Edit Custom VM Options ... or to <PyCharm_installation_folder>/bin/pycharm.vmoptions (or pycharm64.vmoptions). Restart PyCharm and the parser should work correctly.
See the relevant ticket in PyCharm's bug tracker https://youtrack.jetbrains.com/issue/PY-49970
Update: the fix is available in 2021.2.1 RC.
Problem solved by ignoring the error. Copied to an other editor and nothing here. So seems to be a PyCharm mistake.
My problem was caused by indentation mismatch. Most of the document was indented with spaces but there were some tabs copied in that caused the Py:DEDENT error. Replacing the tabs with spaces fixed the error.
I was also scratching my head for significant period of time and finally figured it out.
The thing is outside of "pycharm did not recognize certain char" scope
When you write this:
class Foo:
def complicated_method(self):
for f to self.whatever:
# plenty of code goes here
pass
def another one():
# here too
pass
And then you decide to rewrite it:
class Foo:
def complicated_method(self):
# plenty of code goes here <- mistakenly leaved unindented, many unseen errors here
pass
def another one(self):
# here too
pass
....
def do(self):
for f in self.whatever:
self.complicated_method() <- here will be Py:DEDENT
Refactor long methods, if you can, and Py:DEDENT will never bother you again
Had the same problem after upgrading my pycharm-professional snap on Ubuntu 21.*. Fixed it reinstalling pycharm using jetbrains-toolbox.
On PyCharm 2021.2.2 Professional Edition i see the error in following case
defthe_fun_one(cls):
cls.some_module.some_function()
def the_fun_two(cls):
cls.some_other_module.some_other_function()
I see the Statement expected, found Py:DEDENT on line cls.some_other_module.some_other_function() when a previous function had def not separated by a space typo like defthe_fun_one(cls):
List item
I had an issue where I had an extra -> returnobject in my file. So it was a syntax error.
You will see in the screenshot that pressing enter after pasting a multiline code doesnt run it but merely send each time a "...".
How can I run this multiline pasted code?
someone asked here, but did not get (the right) answer;
Did not work:
Backspace
Use the arrow key to move the cursor, then use the delete key
Escape
F2
Pressing enter twice when inside the Python interpreter executes a block of code, but you have an unmatched open parenthesis on the last line, so you haven't completed defining the block of code. Also, I'm not sure what dic is in the last line, because you haven't included its definition, so you may need to fix that as well.
Running
a=[1,2]
for x in a:
print(x)
actually works (pressing 2 enters worked as expected). So I made a mistake in the code above. I aplogise, I should have checked that before.
I don't delete the question since the one on google can be confusing (the guy did not mentioned it was his mistake, so I though there was a trick to be found. The trick is to check the code).
you could use IPython link which simplifies the process, better yet you have access to every command line as if executed inside the shell.
The other alternative is to encapsulate this inside a function
I know this answer is a bit late, but someone will need the information sometime:
When you make a new line, i.e. title.quote.... you need to press the tab to create an indent, then it will work. Without indenting, you get the "expected an indent" error message.
try:
driver = launch_browser()
except:
print "Browser launch failed"
driver.get("http://www.example.com/")
The last line above is flagged by PyCharm with the following issue:
Local variable "driver" might be referenced before assignment
However, something like this makes the error go away:
driver = None
try:
driver = launch_browser()
except:
print "Browser launch failed"
driver.get("http://www.example.com/")
Is there a way to setup PyCharm so that it will see the assignements inside try blocks?
Secondarily, can PyCharm figure out the type based on the return value of the function (in this case launch_browser()) if it has docstrings?
BTW, code works just fine in both cases. It's just a matter of getting PyCharm to understand the assignment inside the try block without having to resort to a band-aid.
EDIT 1:
A return in the except: block fixes the problem as far as PyCharm is concerned. I was working on something else and inadvertently commented it out. Proof that coding for 16 hours straight is a really bad idea...
If launch_browser() fails, your code will error at the driver.get("http://www.example.com/") line. PyCharm is letting you know this.
The only way to avoid this is by not executing anything below the except, e.g. throwing an exception inside it, or putting everything that relies on driver inside an else block, which will only run if no exception is caught. E.g.
try:
driver = launch_browser()
except:
print "Browser launch failed"
else:
driver.get("http://www.example.com/")
When I test a module that uses Requests, pylint has a fit and claims that the various members of the Request object that I use do not exist. How can I fix this? I already run pylint with the --generated-members=objects option.
For example, this code runs fine:
import requests
response = requests.get('https://github.com/timeline.json')
print response.content
But pylint claims the field does not exist:
ID:E1103 Instance of 'Request' has no 'content' member (but some
types could not be inferred)
pylint warning and error messages can be configured.
First of all you can write a ${HOME}/.pylintrc to disable some messages for all pylint checks. You can generate a default version of this file using the --generate-rc-file option.
(See this question for a bit more information).
You can also do the configuration inside the sources analyzed. For example putting some comments at the beginning of the file. This will disable the messages for the whole file.
The comment are in the form: #pylint: disable=warning-code, and "warning-code" is one of the list found here.
You can also disable messages locally, putting the comment before or on the side of a statement/expression.
For example, this disables the "C0322" warning for the code inside the function:
def my_func():
#C0322 -> no space between operand and operator
#pylint: disable=C0322
return a+b
While putting the comment on the right disables it for the single line of code:
def my_func():
return a+b #pylint: disable=C0322
I think in your case you could either put a comment at the beginning of the functions that use the request, or, if you do not access it many times, you could put a comment on the right of the statements.
This problem is partly due to my lack of completely understanding scoping in python, so I'll need to review that. Either way, here is a seriously trivial piece of code that keeps crashing on my Django test app.
Here's a snippet:
#login_required
def someview(request):
try:
usergroup = request.user.groups.all()[0].name
except:
HttpResponseRedirect('/accounts/login')
if 'client' in usergroup:
stafflist = ProxyUserModel.objects.filter(groups__name='staff')
No brain surgery here, the problem is I get an error such as the following:
File "/usr/local/django/myapp/views.py", line 18, in someview
if 'client' in usergroup:
UnboundLocalError: local variable 'usergroup' referenced before assignment
My question here is, why is usergroup unbound? If it's unbound, that means the try statement had an exception thrown at which point an HttpResponseRedirect should happen, but it never does. Instead I get an HTTP 500 error back, which is slightly confusing.
Yes I can write smarter code and ensure that the user logging in definitely has a group associated with them. But this isn't a production app, I'm just trying to understand / learn Python/Django. Why exactly is the above happening when a user that's not associated with a group logs in instead of a redirect to a login page?
In this case I'm intentionally logging in as a user that isn't part of a group. That means that the above code should throw an IndexError exception like the following:
>>> somelist = []
>>> print somelist[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
HttpResponseRedirect('/accounts/login')
You're creating it but not returning it. Flow continues to the next line, which references usergroup despite it never having been assigned due to the exception.
The except is also troublesome. In general you should never catch ‘everything’ (except: or except Exception:) as there are lots of odd conditions in there you could be throwing away, making debugging very difficult. Either catch the specific exception subclass that you think is going to happen when the user isn't logged on, or, better, use an if test to see if they're logged on. (It's not really an exceptional condition.)
eg. in Django normally:
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login')
or if your concern is the user isn't in any groups (making the [0] fail):
groups= request.user.groups.all()
if len(groups)==0:
return HttpResponseRedirect('/accounts/login')
usergroup= groups[0].name
Try moving you if 'client' part inside you try block. Either that or define usergroup = None right above the try.
In cases where you have a try…except suite and you want code to run iff no exceptions have occurred, it's a good habit to write the code as follows:
try:
# code that could fail
except Exception1:
# handle exception1
except Exception2:
# handle exception2
else: # the code-that-could-fail didn't
# here runs the code that depends
# on the success of the try clause