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.
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
.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With