0

Suppose I have following files

tata/foo.py
tata/yoyo.py

foo/__init__.py
foo/bar.py

In file foo.py I do

import foo.bar

I run PYTHONPATH=. python tata/yoyo.py and I get

Traceback (most recent call last):
  File "tata/yoyo.py", line 1, in <module>
    import foo.bar
ImportError: No module named bar

Issue disappears when I delete tata/foo.py. Could you please suggest a way to resolve my situation when I have global module name and local file name coincides.

V_V
  • 612
  • 9
  • 23

3 Answers3

1

Use:

from __future__ import absolute_import
Vinicius Ronconi
  • 181
  • 1
  • 10
1

This is an example:

files:

test
|
import_test
├── foo
│   ├── bar.py
│   ├── bar.pyc
│   ├── __init__.py
│   └── __init__.pyc
├── __init__.py
├── __init__.pyc
└── tata
    ├── foo.py
    ├── foo.pyc
    ├── __init__.py
    ├── __init__.pyc
    └── yoyo.py

yoyo.py:

#!/usr/bin/env python
# encoding: utf-8
from __future__ import absolute_import
from ..foo import bar


print 'cool'

Test command:

cd test    
python -m import_test.tata.yoyo

output:

cool
hxysayhi
  • 1,888
  • 18
  • 25
0

This seems to be a classical issue described in PEP 328

a local module or package can shadow another hanging directly off sys.path

to deal with it:

  1. Code should be executed as module rather than script (-m option).
  2. Use Python 3 which has so-called "absolute import behaviour" or add

    from __future__ import absolute_import
    
V_V
  • 612
  • 9
  • 23