0

I am new to python, and realized that i can assign print i.e. an inbuilt function as a variable, then when i use print('hello world')this shows the exact error that i faced I am familiar to c++ and even in that we were never allowed to use an inbuilt function as a variable name. those were the fundamental rules for naming a variable If python.org has issued the new version I'm sure they would have done it for a reason, bbut i want to know how do i access my print statement after assigning a value to it?

  • 1
    Because built-in names are available in the built-in namespace, which resolves last after the global namespace when you do `some_name`, you can simply do `del print` and it will now resolve to the built-in namespace because `del` will only delete the name from the global (or local) namespace. Note, aside from this special namespace, there is nothing special about the variables that refer to builit-in functions. They are merely names that refer to objects, function objects in this case – juanpa.arrivillaga Jun 23 '20 at 07:10

2 Answers2

0

you won't be able to access your print function unless you do hacky things, which I recommend not to do them in the middle of your code.

Also it is good to know that python (as c++) has scopes for variables, and variables "die" and they are no longer accessible when scope ends. For instance:


def change_print_value():
  print = 3

change_print_value()
print('Print works as expected')

It is a good practice to avoid using reserved keywords as variable names. Any IDE has the keywords highlighted, so you can easily realize when you are using a keyword where you shouldn't.

Guillem
  • 2,376
  • 2
  • 18
  • 35
0

print is not part of the reserved keywords list in python. Here's a comprehensive list of reserved words.

Functions are first class objects in python, so that means they can be treated and manipulated as objects. Since print is a function (and an object), when you call print = 1, you reassign the variable print to have a value of 1, so the functionality "disappears".

Shan S
  • 658
  • 5
  • 18