clarete / forbiddenfruit

Patch built-in python objects

Home Page:https://clarete.li/forbiddenfruit/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can't add a method to None

zed opened this issue · comments

commented
$ python
Python 2.7.3 (default, Aug  1 2012, 05:14:39) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from forbiddenfruit import curse
>>> None.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'method'
>>> curse(type(None), 'method', lambda *a, **kw: None)
>>> None.method()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method <lambda>() must be called with NoneType instance as first argument (got nothing instead)

Hi, zed. Since None is a global singleton, it's possible that you can live with a static method:

>>> curse(type(None), 'method', staticmethod(lambda *a, **kw: 'foo'))
>>> None.method()
'foo'

If you want to patch it reusing a generic method where self represents the bound instance, you can cheat this way:

>>> from functools import partial
>>> curse(type(None), 'method', partial((lambda self, *a, **kw: repr(self)), None))
>>> None.method()
'None'

@candeira Awesome input! I loved the last snippet, pretty awesome usage of the partial() utility!

@clarete thanks!

Also, you ain't seen nothing yet! :)

@candeira Awesome to have skilled people playing with the library! The project is pretty open to contributions! ✌️