Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Why redefinition of a function is not an error? Is there a hackish way to have that feature? [duplicate]

Tags:

python

For example:

def foo():
    print 'first foo'
def foo():
    print 'second foo'

foo()

silently produces: second foo

Today I copy/pasted a function definition in the same file and changed a few lines in the body of second definition but forgot to change the function name itself. I scratched my head for a long time looking at the output and it took me a while to figure it out.

How to force the interpreter throw at least a warning at redefinition of a function? Thanks in advance.

like image 728
subba Avatar asked Apr 18 '14 13:04

subba


2 Answers

How about using pylint?

pylint your_code.py

Let your_code.py be

1 def dup():
2    print 'a'
3 def dup():
4    print 'a'
5
6 dup()

pylint shows

C:  1,0: Missing docstring
C:  1,0:dup: Missing docstring
E:  3,0:dup: function already defined line 1     <--- HERE!!!!
C:  3,0:dup: Missing docstring

...

If you are using Pydev, You can find duplication interactively. When mouseover the second dup, It says Duplicated signature: dup.

pydev

like image 177
emeth Avatar answered Nov 15 '22 12:11

emeth


It is one of features of Python. Functions are values just as integers, so you can pass them around and rebind to names, just as you would in C++ using function pointers.

Look at this code:

def foo(): # we define function and bind func object to name 'foo'
print "this if foo"

foo()     # >>>this if foo

bar = foo # we bind name 'bar' to the same function object

def foo(): # new function object is created and bound to foo
    print "this is new foo"

foo() # foo now points to new object
# >>>this is new foo
bar() # but old function object is still unmodified:
# >>>this if foo

Thus interpreter works fine. In fact it is common to redefine functions when you are working with interactive interpreter, until you get it right. Or when you use decorators.

If you want to be warned about redefining something in python, you can use 'lint' tools, like pylint (see function-redefined (E0102))

like image 32
m.wasowski Avatar answered Nov 15 '22 10:11

m.wasowski