Import question

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Feb 6 06:19:54 CET 2010


En Fri, 05 Feb 2010 13:21:47 -0300, Andrew Degtiariov
<andrew.degtiariov at gmail.com> escribió:

> Code of our project has split into several packages and we deploy the
> project using buildout.
> All worked fine until I need to dynamically inspect python modules.

Entirely by luck, I'd say :)

> ├───project.api.config
> │   ├───project
> │   │   └───api
> │   │       └───config
> │   │           └───settings
> │   └───project.api.config.egg-info
> ├───project.api.contacts
> │   ├───project
> │   │   └───api
> │   │       └───contacts
> │   │           ├───importer
> │   │           └───views
> │   └───project.api.contacts.egg-info

> Regular code like "import project.api.config" worked fine, but now I'm  
> tryed
> __import__('project.api.config'):
>
> $ bin/python
>
>>>> import project.api.config
>>>> __import__('project.api.config')
> <module 'project from
> 'c:\users\ad\project\src\project.api.contacts\project\__init__.pyc'>

You can't use dots neither in module names nor package names as they're
identifiers [1]. It's like trying to use an attribute named 'foo.bar': you
can handle it with getattr/setattr, but normal attribute access won't work:

py> x.foo.bar = 1
Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
AttributeError: X instance has no attribute 'foo'
py> setattr(x, 'foo.bar', 1)
py> x.foo.bar
Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
AttributeError: X instance has no attribute 'foo'
py> getattr(x, 'foo.bar')
1

[1] http://docs.python.org/reference/simple_stmts.html#the-import-statement

> What's wrong? We really need to split the code for several eggs and want
> that all of our package's names starts from 'project.api'

The only sane solution is to avoid using dots in package names. Sorry, but
having project.api.config, project.api.contacts as directory names is
simply crazy.
Looks like you actually wanted to use this layout:

project/
     api/
       config/
         ...
       contacts/
         ...
       core/
         ...

but made a wrong turn in the road...

-- 
Gabriel Genellina




More information about the Python-list mailing list