Odd behavior with staticmethods

cmdrrickhunter@yaho.com conrad.ammon at gmail.com
Sat Jul 1 16:06:16 EDT 2006


I'm getting rather inconsistent behavior with staticmethod.
@staticmethod has the same problems, but I'm demonstrating it with
staticmethod() because it shows things more clearly
---------------------------------------------------
>>> class A:
	def orig():
		print "hi"
	st = staticmethod(orig)
	st2 = st
	wrapped = [ orig ]
	wrapped2 = [ st ]


>>> A.orig()   # NORMAL - unbound method, should fail

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in -toplevel-
    A.orig()
TypeError: unbound method orig() must be called with A instance as
first argument (got nothing instead)
>>> A.st() # NORMAL - staticmethod, all good
hi
>>> A.st2() # NORMAL - copy of a static method, all good
hi
>>> A.wrapped[0]() # ODD - wrapping orig() in a list makes orig() work?
hi
>>> A.wrapped2[0]() # ODD - copying st works -- A.st2() -- but copying it to a list fails?

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in -toplevel-
    A.wrapped2[0]()
TypeError: 'staticmethod' object is not callable
>>> a = [ A.orig] # NORMAL - fails as expected
>>> a[0]()

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in -toplevel-
    a[0]()
TypeError: unbound method orig() must be called with A instance as
first argument (got nothing instead)
>>> b = [ A.st ] # NORMAL - suceeds as expected
>>> b[0]()
hi
>>>
>>> type(A.orig)
<type 'instancemethod'>
>>> type(A.st)
<type 'function'>
>>> type(A.st2)
<type 'function'>
>>> type(A.wrapped[0])
<type 'function'>
>>> type(A.wrapped2[0])
<type 'staticmethod'>
>>> type(a[0])
<type 'instancemethod'>
>>> type(b[0])
<type 'function'>

------------------------------------------------------------

So if the class definition is not finished, one can copy static methods
just fine.  But if it finds its way into a container (in this case, a
list, but making it a member variable of a child object also breaks),
it gets an extra staticmethod wrapper, or something similar?  Once the
class is done, this behavoir no longer occurs.

Can anyone please explain to me why this happens?




More information about the Python-list mailing list