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
 else:
     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):

a=2

Now, if I try to do:

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

or:

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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:

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.

Method 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)
140515915925784
>>> def a(x):
...     return x
...
>>> id(a)
4512942512
>>> a
<function a at 0x10cfe09b0>
>>>
>>>
>>>
>>> a = 3
>>> id(a)
140515915925928
>>> a
3
>>>

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x