Import a module without executing it?
Jay O'Connor
joconnor at cybermesa.com
Tue Dec 7 16:52:26 EST 2004
finite.automaton at gmail.com wrote:
> Functions and classes are created during the very execution you're
> trying to skip so there's no precise way to do what you want.
>
> That said, you can parse the code without executing it, and that will
> give you some information about defined functions and classes. It will
> _not_ give you actual function objects; the only way to get those is to
> execute the code. It will also not catch anything created "on the
> fly"*, e.g. "exec 'def func(x): pass'"
OK, some more information on what I'm tryng to do would help.
I come from a strong Smalltalk background and in most Smalltalk IDEs is
the capability to browse "Implementors" (what classes implement a method
with a given name or like a given name) and "Senders" (from what methods
is a given method name called)
Given a set of code, not all of which I am familiar with, I wanted to
have similar explorative capabilities in understanding the code. grep
in Linux does a decent job, but under Windows, the file search (look for
a particular string in a py file) does not seem to be too..useful (I
don't get back the results I should)
I shied away from just hand-parsing the code because knowing that a file
has a string, or even a function with a given name, in it is not hard,
knowing that the module has a class that has the function (and knowing
the class as well) is more useful
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).
Knowing that both modules and classes (and functions) had reality enough
to be queried, that was my first line of thought, to load the module and
query the module and query the classes in the module, etc... and do
various matches against whatever I was looking for.
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.
So therefore, my original question.
The real question, I suppose, is "what is a good technique to find what
modules and classes implement or refer to particular names"
Take care,
Jay
More information about the Python-list
mailing list