Every so often I have an object defined in some Python code and I want to work out in which file that object was defined.
Generally this can be done by a bit of grepping but if the object name in question is pretty generic this can be less than productive and it turns out there is a nice ready made way provided for us in the Python Standard Library.
So as an example currently I’m working with Pyro4 and I’m curious to know, for instance, where a particular constant, VERSION, is defined.
>>> import Pyro4 >>> print Pyro4.constants.VERSION 4.8
Well the ‘inspect’ module from the Python standard library allows you do just that, specifically the ‘getfile’ method – http://docs.python.org/library/inspect.html#inspect.getfile
>>> inspect.getfile(Pyro4.constants) 'C:\\Python27\\lib\\site-packages\\pyro4-4.8-py2.7.egg\\Pyro4\\constants.pyc'
As we can now see the VERSION object derives from the constants.pyc at the path given. In this case the definition is actually in the middle of an egg, pyro4-4.8-py2.7.egg, which means direct access to the underlying source code is not as straightforward as if it were implemented in plain old python scripts.
Nevertheless we can still make use of another inspect module function, the ‘getsource’ method (http://docs.python.org/library/inspect.html#inspect.getsource) to get some more information about the object we’re interested in as follows:
>>> inspect.getsource(Pyro4.constants) '"""\nDefinitions of various hard coded constants. Pyro - Python Remote Objects. Copyright by Irmen de Jong. email@example.com - http://www.razorvine.net/projects/Pyro""" # Pyro version\nVERSION = "4.8" # standard object name for the Daemon object DAEMON_NAME = "Pyro.Daemon" # standard name for the Name server itself NAMESERVER_NAME = "Pyro.NameServer"
… etc, etc.