Python: function and variable with the same name

After you do this:

a = 2

a is no longer a function, it's just an integer (you reassigned it!). So naturally the interpreter will complain if you try to invoke it as if it were a function, because you're doing this:

2()
=> TypeError: 'int' object is not callable

Bottom line: you can't have two things simultaneously with the same name, be it a function, an integer, or any other object in Python. Just use a different name.


names in Python are typically identifiers for a specific type, more like naming a box which stores a variable/function/method or any object in Python. When you are reassigning, you are just renaming a box.

You can find that out by doing the below.

Initially, a is assigned a value 9, at location 140515915925784. As soon as I use the same identifier for a function , a now refers to a box containing the address of that function in 4512942512

Reassigning a to 3 again points a to refer to a different address.

>>> a = 9
>>> id(a)
140515915925784
>>> def a(x):
...     return x
...
>>> id(a)
4512942512
>>> a
<function a at 0x10cfe09b0>
>>>
>>>
>>>
>>> a = 3
>>> id(a)
140515915925928
>>> a
3
>>>