Emin wrote:

> On Jan 17, 11:20 am, Peter Otten <[EMAIL PROTECTED]> wrote:
>> Emin wrote:
>> > I often find myself wanting to have a child module get some parameters
>> > defined in a parent module. For example, imagine  I have the following
>> > directory structure and want something in baz.py to look at a value in
>> > config.py. I end up putting in things like import sys;
>> > sys.path.append('../..'). Is there a better way?
>>
>> > foo/
>> >      __init__.py
>> >      config.py
>> >      bar/
>> >           __init__.py
>> >           baz.py

>> from __future__ import absolute_import  
>> from .. import config

> I put the lines you suggested in baz.py, but got an error:
> 
> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import baz
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "baz.py", line 3, in <module>
>     from .. import config
> ValueError: Attempted relative import in non-package

If you put foo/bar in the path and then

import baz

how do you think that baz is to know that it's actually foo.bar.baz?
Make sure that the parent directory of foo is in sys.path (e. g. by starting
the interpreter in that directory) and then import baz using its official
name.

$ tree
.
`-- foo
    |-- __init__.py
    |-- bar
    |   |-- __init__.py
    |   `-- baz.py
    `-- config.py

2 directories, 4 files

$ cat foo/config.py
print "importing config"

$ cat foo/bar/baz.py
from __future__ import absolute_import
from .. import config

$ python2.5
Python 2.5 (r25:51908, Oct  3 2006, 08:48:09)
[GCC 3.3.3 (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo.bar.baz
importing config

Peter

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to