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.
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.
i am trying to execute this very short code that took out from my bigger code because i was having problems with it. I was able to reproduce the problem (it gave the exact same error).
BACKGROUND INFO: i am just trying to get the first sentence out of this wikipedia search. but because the word i am searching for (kip, means chicken in Dutch) has a wide variety of meanings or something i get an error. i want to bypass this error using try: except: but it keeps displaying the error message anyway.
here is the code that just doesnt seem to work:
import wikipedia
wikipedia.set_lang('nl')
try:
summry = wikipedia.summary('kip', sentences=1)
print(summry + "\n")
except:
print("error")
i have tried replacing except: with this
except wikipedia.exceptions.DisambiguationError:
but it still doesnt work :( it always displays the error code regradless and prints "error" afterwards
/opt/virtualenvs/python3/lib/python3.8/site-packages/wikipedia/wikipedia.py:389:
GuessedAtParserWarning: No parser was explicitly specified, so I'm using the best available HTML
parser for this system ("html5lib"). This usually isn't a problem, but if you run this code on
another system, or in a different virtual environment, it may use a different parser and behave
differently.
The code that caused this warning is on line 389 of the file
/opt/virtualenvs/python3/lib/python3.8/site-packages/wikipedia/wikipedia.py. To get rid of this
warning, pass the additional argument 'features="html5lib"' to the BeautifulSoup constructor.
lis = BeautifulSoup(html).find_all('li')
error
i am using repl.it to program this
if anyone has any idea about why it keeps displaying the error anyway please please let me know :D
First of all, thank you all for commenting :D it helped a lot
At the end the solution that worked for me was inspired from Askold Ilvento's comment
although
with warnings.catch_warnings(): warnings.simplefilter("ignore")
didn't work when i adapted it a little bit it did the job!
this is the code that solved the problem and allowed me to ignore what was actually a warning (not an exception) and stop displaying it
import warnings
warnings.catch_warnings()
warnings.simplefilter("ignore")
i just added this at the start of the script and it solved the problem :D
once again all the credit for this code goes to Askold Ilvento i just had to add a little bit to it to make it work
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/")
In Python 3.3.5 I am building a class out of some code that works as standalone functions, but it aborts without an error message when the class version is run. It relies on a 3rd party package pcFastDB, distributed as a pyd.
unit1.py
import sys
import pcFastDB as p3
def get_context():
return p3.pcContext.create()
def get_DB(ctx, dbName):
return p3.pcDB.open(ctx, dbName)
.. more..
can be used as:
ctx = get_context()
db = get_DB(ctx, 'tester')
..do things with db
but
Unit2.py
import pcFastDB as p3
class DBOperation(object):
def __init__(self, DB_name):
'''
Get the context, open the database and fill a channel list
'''
self.ctx = p3.pcContext.create()
print('Context ' + str(self.ctx ))
print(' - opening ' + DB_name)
self.db = p3.pcDB.open(self.ctx, DB_name) #aborts here
print('DB opened successfully...' +str(self.db))
aborts silently when I try to open the DB.
db = DBOperation('tester')
The tester db exists and is in the project folder where I am running it.
There is no exception, no error, it just stops executing. PyDev doesn't like the pyd file very well. I don't get any code insight so debugging is kind of mysterious, but in IPython3 I can see all of the functions and class members, so I know its ok. Unfortunately debugging in IPython3 is an unfathomable mystery to me.
Anyway, I know that I am calling the right functions and I know the functions work, because it all works fine in Unit1, it just doesn't work as a class member. Is this even possible?
I've broken the DB lines out of the init and called them separately, and I've broken ctx out of the class and passed it into the functions but that doesn't work either. It behaves identically when run from within PyDev, IPython3 or the command line.
Any ideas?
Thanks everyone, I've gotten it working by basically rewriting the identical code into a new module. There seems to have been something weird with the file itself. I'm blaming PyDev.
Marc
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!