Import a module without executing it?
Andy Gross
andy at andygross.org
Tue Dec 7 17:17:38 EST 2004
> So, in Smalltalk, the way you find out about what's in the system is
> reflection...you ask the classes what methods they implement (if
> looking for 'implementors'), you ask the methods for the source and
> can string search the code (if looking for senders).
There's no real way to get the source code from a compiled code object
, although there are some tools, like decompyle, which will try for
you. I think some people on this list were discussing the potential
utility of having a __source__ attribute for code objects, but Python
currently doesn't do this. You can probably also get some mileage out
of the inspect module (try 'pydoc inspect'), but that *does* compile
the code you're inspecting.
> It worked fine for a file that just defined functions and classes.
> However, files that had code not contained in classes or functions
> caused a bit of a problem because loading the module would execute
> that code and that's not what I wanted.
To get at top-level module code like this, you'll have to parse the
file and walk the AST - there's no other way. In a well implemented
library or app, however, there typically shouldn't be much important
code being executed at the top level. Typically the top-level code
will be initialization of singleton globals or decorator-type function
wrappers, and you can get at most of the important names reflectively
through the inspect module.
/arg
More information about the Python-list
mailing list