m0bi5
m0bi5

Reputation: 9472

Two functions with the same name in Python

I was just playing around with Python and realized something weird.

I have the below function:

def myfun():    #f1
    return 1
def myfun():    #f2
    return 0

print (myfun())

I changed the values in f1 and f2, but still it always seems to be printing the return value of f2. Is there a specific reason?

Upvotes: 1

Views: 5753

Answers (3)

PM 2Ring
PM 2Ring

Reputation: 55489

In compiled languages you would generally get an error message if you try to define two functions with the same name. But in Python functions are first-class objects and they are defined dynamically.

When you define a new function with the same name as a previously defined function, the function name is now bound to the new function object, and the old function object is reclaimed by the garbage collector.

So what happens to your functions is no different to what happens with the simple integer examples posted in the other answers on this page.

Similarly, we can do the same thing with functions defined using the lambda mechanism. Eg:

>>> myfun=lambda:1; myfun=lambda:0; print(myfun())
0

Upvotes: 6

Dan D.
Dan D.

Reputation: 74655

The second definition causes the name myfun to be bound to its function replacing the binding produced by the previous definition. This is exactly the same as what happens in:

a = 1
a = 0

print a

Upvotes: 0

WeaselFox
WeaselFox

Reputation: 7380

Why is that weird? The second function decleration overrides the first, so by the time print is called only f2 exists.

Upvotes: 0

Related Questions