Python: function and variable with the same name

Posted on

Question :

Python: function and variable with the same name

Why can’t I call the function again? Or, how can I make it?

Suppose I have this function:

def a(x, y, z):
 if x:
     return y
     return z

and I call it with:

print a(3>2, 4, 5)

I get 4.

But imagine that I declare a variable with the same name that the function (by mistake):


Now, if I try to do:

a=a(3>4, 4, 5)


a(3>4, 4, 5)

I will get this error: “TypeError: ‘int’ object is not callable”

Is it not possible to assign the variable ‘a’ to the function?

Answer #1:

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:

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

Answered By: Óscar López

Answer #2:

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)
>>> def a(x):
...     return x
>>> id(a)
>>> a
<function a at 0x10cfe09b0>
>>> a = 3
>>> id(a)
>>> a
Answered By: durga

Answer #3:

You’re assigning the name a to a function definition, and then reassigning it to an integer.

It’s syntactically correct, but it’s not what you want.

It’s best to give functions semantic names that describe what you’re doing with the arguments being passed to them, and to give variables semantic names that describe what object they’re pointing to. If you do that, you’ll have more readable code and you certainly won’t make this mistake again.

Answered By: Aaron Hall

Leave a Reply

Your email address will not be published. Required fields are marked *