Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #63639
| From | Roy Smith <roy@panix.com> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Monkeypatching a staticmethod? |
| Date | 2014-01-10 00:23 -0500 |
| Organization | PANIX Public Access Internet and UNIX, NYC |
| Message-ID | <roy-CE7D46.00231110012014@news.panix.com> (permalink) |
This is kind of surprising. I'm running Python 2.7.1. I've got a class
with a staticmethod that I want to monkeypatch with a lambda:
----------------------------------
class Foo:
@staticmethod
def x():
return 1
Foo.x = lambda: 2
print Foo.x()
----------------------------------
What's weird is that it seems to remember that x is a staticmethod
despite having been patched:
Traceback (most recent call last):
File "static.py", line 8, in <module>
Foo.x()
TypeError: unbound method <lambda>() must be called with Foo instance as
first argument (got nothing instead)
What seems to work is to patch it with another staticmethod:
----------------------------------
class Foo:
@staticmethod
def x():
return 1
@staticmethod
def x():
return 2
Foo.x = x
print Foo.x()
----------------------------------
$ python static.py
2
I didn't even know you could define a staticmethod outside of a class!
I suspect this post is really just my way of admitting that while I've
used staticmethods plenty, I've never fully understood the details of
what happens when you construct them :-)
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
Monkeypatching a staticmethod? Roy Smith <roy@panix.com> - 2014-01-10 00:23 -0500
Re: Monkeypatching a staticmethod? Ian Kelly <ian.g.kelly@gmail.com> - 2014-01-10 00:31 -0700
Re: Monkeypatching a staticmethod? Piet van Oostrum <piet@vanoostrum.org> - 2014-01-10 15:04 +0100
csiph-web