Everything’s a name in Python. Except the keywords.

leangaurav
Industrial Python
Published in
4 min readJul 15, 2019

This story was part of a poster I presented at Pycon Chennai 2019. Somethings are yet to be updated here. Final draft of poster is available here for your reference. It has more some more code examples.

Does this work ?

Warning - 0
You might not get many of the things I write here if you don’t run all the code in a python interpreter. (python3) Or you may understand… but still try to execute.

This is the exhaustive list of keywords present in python.

([‘False’, ‘None’, ‘True’, ‘and’, ‘as’, ‘assert’, ‘async’, ‘await’, ‘break’, ‘class’, ‘continue’, ‘def’, ‘del’, ‘elif’, ‘else’, ‘except’, ‘finally’, ‘for’, ‘from’, ‘global’, ‘if’, ‘import’, ‘in’, ‘is’, ‘lambda’, ‘nonlocal’, ‘not’, ‘or’, ‘pass’, ‘raise’, ‘return’, ‘try’, ‘while’, ‘with’, ‘yield’], 35)

To get it type this on interpreter:

>>> import keyword
>>> keyword.kwlist, len(keyword.kwlist)

So there’s a module keyword and it has a list attribute kwlist that contains all the keywords in python. 35 in total on 14 July 2019.

Other ways to do the same?

YES

help('keywords')

Any other way?

GO CHECK YOURSELF and post in comments.

Now tell me what is print ?

Function ??
YES..

Anything else?

Keyword?
NOOOOO.. Don’t even think. go check the list

What then?

A name?
YES.. a built-in name

So the correct answers are Function and Name(or programming term for Name is Identifier).

But don’t be too happy to see your answer there. Saying print is a Name is more accurate than saying print is a Function.

What does the interpreter say? [if you get the song….]

>>> print
<built-in function print>

(don’t write print() just write print )

Says a function.. You win !!

But please explain me what is all this then………………….

>>> x = 10
>>> print(x)
10
>>> p = x
>>> print(p)
10
>>> p = print
>>> p(x)
10
>>>

Believe me now!! Everything is just a name apart from keywords, operators and literals(constants like 10,-99.99, ‘abcd’).

Need more Proof? (restart interpreter before running below one)

>>> dir()
[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]
>>> x = 0 # create x
>>> x

0
>>> dir() # x is there
[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘x’]
>>> del x
>>> dir() # x is gone
[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]
>>> x
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘x’ is not defined
>>>

You can create names and delete them. (what’s dir() ? Check yourself here).

One question now…
What is x in previous code?

Variable?
YES

Name/Identifier?
YES YES

So if print is a name… we should try deleting it?
Yes for sure…

>>> del print
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘print’ is not defined

Sad!! (But print is a name… wait and watch)

But did we see print in result of dir() ?? Let do it again.

>>> del print
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘print’ is not defined
>>> dir()
[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’]
>>>

Print is not a keyword for sure… so where the hell does this name come from?

>>> dir(__builtins__)
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’, ‘BlockingIOError’, ‘BrokenPipeError’, ‘BufferError’, ‘BytesWarning’, ‘ChildProcessError’, ‘ConnectionAbortedError’, ‘ConnectionError’, ‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’, ‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’, ‘FileExistsError’, ‘FileNotFoundError’, ‘FloatingPointError’, ‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’, ‘IndentationError’, ‘IndexError’, ‘InterruptedError’, ‘IsADirectoryError’, ‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’, ‘ModuleNotFoundError’, ‘NameError’, ‘None’, ‘NotADirectoryError’, ‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’, ‘PendingDeprecationWarning’, ‘PermissionError’, ‘ProcessLookupError’, ‘RecursionError’, ‘ReferenceError’, ‘ResourceWarning’, ‘RuntimeError’, ‘RuntimeWarning’, ‘StopAsyncIteration’, ‘StopIteration’, ‘SyntaxError’, ‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’, ‘TimeoutError’, ‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’, ‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’, ‘UnicodeWarning’, ‘UserWarning’, ‘ValueError’, ‘Warning’, ‘WindowsError’, ‘ZeroDivisionError’, ‘_’, ‘__build_class__’, ‘__debug__’, ‘__doc__’, ‘__import__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’, ‘bool’, ‘breakpoint’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’, ‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘exec’, ‘exit’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’, ‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’, ‘locals’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’, ‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’, ‘repr’, ‘reversed’, ‘round’, ‘set’, ‘setattr’, ‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]
>>>

Got it now. Try deleting it.

>>> del __builtins__.print
>>> print
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
NameError: name ‘print’ is not defined
>>>

Print is a name. Hence proved.

Last thing. It means dir, help, etc etc… everything is a name.
Or identifier.

One more… My favorite code

>>> p = print
>>> p(p)
<built-in function print>
>>>

--

--

leangaurav
Industrial Python

Engineer | Trainer | writes about Practical Software Engineering | Find me on linkedin.com/in/leangaurav | Discuss anything topmate.io/leangaurav