Search code examples
pythoninheritancepython-3.xmetaprogrammingmonkeypatching

Helper function injected on all python objects?


I'm trying to mimic methods.grep from Ruby which simply returns a list of available methods for any object (class or instance) called upon, filtered by regexp pattern passed to grep. Very handy for investigating objects in an interactive prompt.

def methods_grep(self, pattern):
    """ returns list of object's method by a regexp pattern """
    from re import search
    return [meth_name for meth_name in dir(self) \
            if search(pattern, meth_name)]

Because of Python's limitation not quite clear to me it unfortunately can't be simply inserted in the object class ancestor:

object.mgrep = classmethod(methods_grep)
# TypeError: can't set attributes of built-in/extension type 'object'

Is there some workaround how to inject all classes or do I have to stick with a global function like dir ?


Solution

  • There is a module called forbiddenfruit that enables you to patch built-in objects. It also allows you to reverse the changes. You can find it here https://pypi.python.org/pypi/forbiddenfruit/0.1.1

    from forbiddenfruit import curse    
    curse(object, "methods_grep", classmethod(methods_grep))
    

    Of course, using this in production code is likely a bad idea.