Skip to content

Instantly share code, notes, and snippets.

@nikitakit
Created October 12, 2015 06:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikitakit/642cb96febdf2f812d0b to your computer and use it in GitHub Desktop.
Save nikitakit/642cb96febdf2f812d0b to your computer and use it in GitHub Desktop.
Inspecting interactively created classes
import inspect, sys
def new_getfile(object, _old_getfile=inspect.getfile):
if not inspect.isclass(object):
return _old_getfile(object)
# Lookup by parent module (as in current inspect)
if hasattr(object, '__module__'):
object_ = sys.modules.get(object.__module__)
if hasattr(object_, '__file__'):
return object_.__file__
# If parent module is __main__, lookup by methods (NEW)
for name, member in inspect.getmembers(object):
if inspect.isfunction(member) and object.__qualname__ + '.' + member.__name__ == member.__qualname__:
return inspect.getfile(member)
else:
raise TypeError('Source for {!r} not found'.format(object))
inspect.getfile = new_getfile
@nc7s
Copy link

nc7s commented Oct 13, 2015

In standard Python (3.5.0) shell the result of a quick test is "". I assume the shell didn't linecache that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment