Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define True, if not defined, causes syntax error

Tags:

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?

like image 428
ap0 Avatar asked Jun 25 '15 06:06

ap0


People also ask

Is not defined SyntaxError?

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.

How do I fix Python SyntaxError?

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.

Which of the following is an example of a SyntaxError?

Syntax errors are mistakes in using the language. Examples of syntax errors are missing a comma or a quotation mark, or misspelling a word.

What are syntax errors in Python?

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.


2 Answers

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.

like image 117
nneonneo Avatar answered Sep 26 '22 00:09

nneonneo


SyntaxError shows up during the byte-compilation stage, before the code is ever run -- so you can't get around it with try/except.

like image 30
Ethan Furman Avatar answered Sep 22 '22 00:09

Ethan Furman