sdvillal / whatami

Easily provide python objects with self-identification
Other
9 stars 1 forks source link

Monkey patch / decorate extension types #7

Open sdvillal opened 9 years ago

sdvillal commented 9 years ago

Sometimes it can be useful to add a what method to an extension type. I would recommend in these cases to be clean and create a whatable function/class that delegates the work to the function in C-land.

However, it might be useful to allow monkey-patching extension types. Some info here and here.

forbiddenfruit is a small tool to nastily monkey-patch any extension type (including builtins). It is released in pypi GPL licensed, although whatami can use it under the MIT license. I have been playing with it and works great, so it can be a neat addition together with the ability to specify custom what functions to the whatable decorator (in any case introspection won't work with these kind of objects). These few lines in whatable made the trick:

if inspect.isclass(obj):
    try:
        obj.what = whatablefunc
    except:
        from forbiddenfruit import curse
        curse(obj, 'what', whatablefunc)
        print('WARNING, patched builtin/extension type %s' % type(obj))
       # This will anyway fail for extension types 
       # (can we make forbiddenfruit work with instances?)

Also add a like like this to optional dependencies in setup.py:

           'ubermonkey': ('forbiddenfruit',),

Note: the comments on the forbiddenfruit issue tracker are an interesting read.

sdvillal commented 9 years ago

It does not seem to be a good idea. Testing at 2b29f5a8d33 showed very unstable interpreter and random crashes after enacting forbiddenfruit. Will assess alternative ways (e.g. dynamically create mixins inheriting from extension types and adding the what method).