[Tutor] sibling import

Alex Kleider akleider at sonic.net
Fri Oct 13 12:55:55 EDT 2017


On 2017-10-12 15:58, Mats Wichmann wrote:
> On 10/12/2017 05:15 AM, Atar new wrote:
>> Hi Team,
>> 
>> Here is my problem. I want to use sibling import but it is not working 
>> . I
>> know taht if we add the directory in sys.path ,it will work.
>> 
>> But I have to package the whole application and will create a setup.py 
>> file
>> out of it .
>> What is the standard way to do it?
>> 
>> 
>>    1. mkdir A
>>    2. mkdir B
>>    3.
>>    4. touch A/__init__.py
>>    5. touch B/__init__.py
>>    6.
>>    7. touch A/foo.py
>>    8. touch B/bar.py
>>    9.
>>    10. cat B/bar.py
>>    11. from A import foo
>>    12.
>>    13.
>>    14. python B/bar.py
>>    15. ImportError: No module named A
>> 
>> 
>> 
>> Thanks
>> Anju
> 
> This isn't the way: from the context of bar.py in B, there is no A.  
> You
> generally speaking want a relative import (from .A import foo) for
> modern python versions, but because of the path structure you've set 
> up,
> even that won't work, the script doing the importing would need to be 
> in
> the top directory of your package. "Sibling" imports just don't work
> well.  There was a PEP somewhere about this, which as I recall required
> some horrid looking hack.
> 
> So with a bit of hunting,
> https://www.python.org/dev/peps/pep-0366
> and more reading at
> https://www.python.org/dev/peps/pep-0338

I think Anju can solve his problem simply by adding his working 
directory (parent of A and B) to PYTHONPATH.
Some one on this list some time ago provided me with the following bash 
magic to accomplish this:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}$(pwd)"


More information about the Tutor mailing list