A Python Syntax question [Answered]

I’m curious as to why Python allows such syntax as…

str = 'This is a string'

or even worse…

print = 'This is a string'

that is to say, why Python does not throw a hissy fit, when one uses key words in such a negligent way?

Because str and print aren’t keywords, but just names from the global namespace. It can be quite helpful to override them sometimes, such as

import logging
logger = logging.getLogger('some_logger')

def print(*args, sep=' ', **kw):
    logger.info(sep.join('%s' for each in args), *args)

And if you need the original print instead, you can get it with

import builtins
builtins.print

In fact, print was changed from a keyword to a builtin in Python 3 for exactly this purpose.

1 Like

Please do not be mistaken. str and print are not keywords. They are normal identifiers which are pre-defined as builtins. You can still access the original objects after you reassign the identifiers:

str = 'This is a string'
print = 'This is a string'

import builtins
builtins.print('Concatenate strings: ' + builtins.str(1))

It is certainly a good idea to avoid such re-assignment / shadowing in normal code. To be warned about those you can use linters - for example pylint:

$ cat pylint-test.py
print = 'This is a string'
$ pylint pylint-test.py
************* Module pylint-test
pylint-test.py:1:0: C0103: Module name "pylint-test" doesn't conform to snake_case naming style (invalid-name)
pylint-test.py:1:0: C0114: Missing module docstring (missing-module-docstring)
pylint-test.py:1:0: W0622: Redefining built-in 'print' (redefined-builtin)
pylint-test.py:1:0: C0103: Constant name "print" doesn't conform to UPPER_CASE naming style (invalid-name)

------------------------------------------------------------------
Your code has been rated at 0.00/10 (previous run: 0.00/10, +0.00)

My thanks to you both for the comprehensive answer.