Dynamic package exploration

Thomas Wouters thomas at xs4all.net
Fri Jul 21 18:30:44 EDT 2000


On Fri, Jul 21, 2000 at 10:24:58PM +0000, Sebastien Pierre wrote:

>  I cannot reference any Python object using an absolute name...

It's not an 'absolute name'. the 'os.name' isn't like a full path to a
filename. It merely references the attribute 'name' of object 'os'. 

>  Example :
>   >>print os.name
>   fails....
>  But if I do
>   >>import os
>   >>print os.name
>  It works - so I guess you have to "import" first before being able to
> reference anything.

If they are modules, yes. If you do 'os.name' without importing os, Python
can't know which 'os' you are talking about ! After all, 'os' isn't a magic
name, it just happens to be the name of an often used module.

>  But if I do :
>   >>eval ( "import os" )
>  It doesn't work...so it prevents me from doing something
> dynamic...Ouch!

That's because you're using the wrong function. 'eval' can only evaluate
*expressions*, and 'import' is a *statement*. You need to use 'exec'.

> Let's say I have a package A that contains 10 python files. What I want
> to do is dynamically inspect the content of A (the 10 python files), and
> check if those python files have the attribute called
> '__my_attribute__'. Then I want to register these attributes in a list.

Try using 'dir()' and/or 'getattr()'. The documentation on those should give
a few hints.

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list