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 ?
dir(), e.g.dir(some_object)(edit: ok I see you already know that ;)methods_grepfunction. I need a function available on all objects which returns all available methods filtered by the pattern given as argument.str.mgrep('split')would return['_formatter_field_name_split', 'rsplit', 'split', 'splitlines'].mockmodule, although it might be dicey setting up aMockthat delegates every thing to the originalobjecttype in addition to handling themgrepmethod as well.