Mohammad Yusuf
Mohammad Yusuf

Reputation: 17054

What does a python class name as a single line statement do

Can somebody explain the 2nd line (unicode is a class defined in the code)?

try:
    unicode
    _unicode = True
except NameError:
    _unicode = False

Upvotes: 0

Views: 71

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

Python 2 defines a unicode type. Python 3 does not (str has taken this role). Trying to use the name unicode in Python 3 will thus raise a NameError exception.

In other words, using the type name on a line does nothing by itself other than trigger a name lookup. If that name lookup fails, you know that the type is not available:

$ python2.7 -c 'unicode'
$ python3.5 -c 'unicode'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
NameError: name 'unicode' is not defined

Upvotes: 4

Related Questions