Wednesday, August 02, 2006

Duplicate Methods in Python

Stumbled across a little gotcha in Python. Python, when it loads a source file, executes the code as a command. For instance, assume the following code:


class Foo:
def method1( self ):
pass


It sees the class statement as a command, with two lines of text following as parameters. Similarly, it sees the def statement as a (sub)command with one line as a parameter. The def 'command' adds (or replaces) the method method1 in the current scope, in this case, class Foo.

Which leads me to my gotcha. The following code is valid, but probably not what you want:


class Foo:
def method1( self ):
print 'Yes'
def method1( self ):
pass


In this case, the first def statement will work, adding a method1 that prints to the class. The second one will work, too, replacing the existing method1 with one that does nothing.

Unfortunately for me, I had added some stubs to the bottom of my source file, then forgot that they were there, and added the real method higher up, and wondered why the method apparently wasn't being executed. Debugging a bit showed me that it was getting called by the calling code, but the call wasn't arriving in the method itself. The 2nd def had replaced the first with a method that did nothing.

Chalk one up to experience.

0 Comments:

Post a Comment

<< Home