I have found the following construct today in someone elses code:
try: True, False
except NameError: True = 1==1; False = 1==0
As I understand this, it defines True
and False
if they are not defined already. So if they are defined it shouldn't throw the NameError
-Exception, right?
I have tryed this for myself in a shell and it shows me SyntaxError: can't assign to keyword
My question is why does it even shot the syntax error if True and False are defined? If True and False are available on my system, shouldn't it just go past the exception handling and not show a syntax error?
This syntax error is telling us that the name count is not defined. It basically means that the count variable is not defined. So in this specific case we are using the variable count in the condition of the while loop without declaring it before. And because of that Python generates this error.
You can clear up this invalid syntax in Python by switching out the semicolon for a colon. Here, once again, the error message is very helpful in telling you exactly what is wrong with the line.
Syntax errors are mistakes in using the language. Examples of syntax errors are missing a comma or a quotation mark, or misspelling a word.
Syntax errors are produced by Python when it is translating the source code into byte code. They usually indicate that there is something wrong with the syntax of the program. Example: Omitting the colon at the end of a def statement yields the somewhat redundant message SyntaxError: invalid syntax.
This code is written for Python 2.x and won't work on Python 3.x (in which True
and False
are true keywords).
Since True
and False
are keywords in Python 3, you'll get a SyntaxError
which you cannot catch.
This code exists because of very old versions of Python. In Python 2.2 (released in 2001!), True
and False
did not exist as predefined names, so this code would provide compatible definitions so that later code could simply use True
and False
.
When converting your Python 2.x code to Python 3.x, remove these lines; they are historical and have no use in Python 3.x. If you see these lines in someone else's code, they are a sure sign that the program was not written or ported for Python 3.
SyntaxError
shows up during the byte-compilation stage, before the code is ever run -- so you can't get around it with try
/except
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With