Using print as a variable name in python
Question:
While following a tutorial for python, I got to know that we can use print for a variable name, and it works fine. But after assigning the print variable, how do we get back the original print function?
>>> print("Hello World!!")
Hello World!!!
>>> print = 5
>>> print("Hi")
Now, the last call gives the error TypeError: ‘int’ object is not callable, since now print has the integer value 5.
But, how do we get back the original functionality of print now? Should we use the class name for the print function or something?
As in, SomeClass.print("Hi")
?
Thanks in advance.
Answers:
You can actually delete the variable so the built-in function will work again:
>>> print = 5
>>> print('cabbage')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del print
>>> print('cabbage')
cabbage
>>> print = 5
>>> print = __builtins__.print
>>> print("hello")
hello
If you want to use as a temp way, do them but after that, apply print
function to print
variable:
print = __builtins__.print
While following a tutorial for python, I got to know that we can use print for a variable name, and it works fine. But after assigning the print variable, how do we get back the original print function?
>>> print("Hello World!!")
Hello World!!!
>>> print = 5
>>> print("Hi")
Now, the last call gives the error TypeError: ‘int’ object is not callable, since now print has the integer value 5.
But, how do we get back the original functionality of print now? Should we use the class name for the print function or something?
As in, SomeClass.print("Hi")
?
Thanks in advance.
You can actually delete the variable so the built-in function will work again:
>>> print = 5
>>> print('cabbage')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del print
>>> print('cabbage')
cabbage
>>> print = 5
>>> print = __builtins__.print
>>> print("hello")
hello
If you want to use as a temp way, do them but after that, apply print
function to print
variable:
print = __builtins__.print