Industrial Python
Published in

Industrial Python

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

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>
>>>

--

--

--

Lear about Python and the tools used in practical software development

Recommended from Medium

DevOps / SRE — Top Links Last Week

from Will Bermender on Twitter January 14, 2017 at 07:15AM

AWS: Auto-Scaling groups and EC2 Instances for High Availability (HA)

Leverage Google Colab GPU Runtime for Non-Notebook Python Projects

My GWAPT Journey

Sanity Saving Menu Bar Magic on macOS

Reasons Why Saudi Arabia Companies Should Hire Dubai Mobile App Development Providers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
leangaurav

leangaurav

Developer, Trainer and Fitness & Yoga Enthusiast

More from Medium

NBA Win Predictions: Results

HOW TO FIND UNIQUE VALUES AND THEIR PERCENTAGE DISTRIBUTIONS USING VALUE_COUNTS() IN PYTHON

What you don’t know about air alerts in Ukraine.

A Silent Killer in India: Air Pollution