Preet Sangha Preet Sangha - 1 year ago 84
Python Question

Rewrite python function without inspect module

How would I write this introspective function without using the inspect module.

import inspect

def trace(cls):
for name, m in inspect.getmembers(cls, inspect.ismethod):
return cls

The above is from this SO question/answer

Is it possible to do this without any imports also?

Note this is not a real use case rather a pure and simple case of curiosity on my part.

Answer Source

something like this:

>>> class Tester(object):
...   def mymethod(self):
...     return True
>>> hasattr(Tester, 'mymethod')
>>> hasattr(Tester.mymethod, 'im_func')

from the python docs on the data model scroll down a bit to get to "user defined methods".

Special read-only attributes: im_self is the class instance object, im_func is the function object; im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods; __doc__ is the method’s documentation (same as im_func.__doc__); __name__ is the method name (same as im_func.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.

im_func and im_self as of 2.6 are also availabale as __func__ and __self__ respectively. I sort of tend to gravitate here than use the inspect module myself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download