NIlesh Sharma
NIlesh Sharma

Reputation: 5665

Same function names in python , No error?

To be honest, I was expecting some sort of error, like 'you can't rename two nested functions with same name in a same body like that' , Can we define any number of functions with same name in python ?

In [40]: def add(i,j):
   ....:     def add(i,j):
   ....:         print i+j
   ....:     def add(i,j):    
   ....:         print i-j
   ....:     return add(i,j)
   ....: 

In [41]: add(5,4)
1

Is this Overloading of function, or Overriding of function ??

Upvotes: 0

Views: 1075

Answers (5)

Nicolas Garnier
Nicolas Garnier

Reputation: 446

Just to be clear, the second nested add() overwrites the first, but the outer one remains unchanged.

Here is a minimal example:

def do_sth(s):
    def do_sth(s):
        print('Hello, %s!' % s)
    print('Ola')
    do_sth(s)

>>> do_sth('chuinul')
Ola
Hello, chuinul!
>>> do_sth('chuinul')
Ola
Hello, chuinul!

When you call do_sth() the second time, this is still the outer function you defined that is being called. Otherwise you would have only had:

>>> do_sth('chuinul')
Hello, chuinul!

Upvotes: 0

kindall
kindall

Reputation: 184280

Of course. A def statement is functionally an assignment (of the function to the name), and you can have any number of assignments to the same name. (It`s important to realize that function definitions are executed in Python, they are not statically evaluated at compile time.)

There are hacky ways to catch this in class definitions, such as this method I posted in May. If you're using Python 3, there's a better way.

For functions, that won't work, so I believe you're stuck with this behavior.

Upvotes: 4

trnc
trnc

Reputation: 21575

the last functions overwrites the others... so, there's no error! :)

Upvotes: 0

Robert
Robert

Reputation: 8767

A function definition introduces the function name in the current symbol table. The value of the function name has a type that is recognized by the interpreter as a user-defined function. This value can then be assigned to another name, or even reassigned by redefining the function.

In cases where a function is redefined, the latest definition will be used as it is the one that is recognized by the interpreter.

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251448

Defining a function is like like assigning a value to a variable. You can do this in Python:

a = 1
a = 2

Likewise you can do this:

def f():
    return 1
def f():
    return 2

In both cases, the last value specified overwrites any previous values. So the last one wins.

The fact that it's a nested function has no bearing on the issue. The same applies in any context.

Upvotes: 4

Related Questions