0

eg. I have a package foo which has a module named foo.py

/home/user/tmp/testPath/                                                                                                                                                                                 
|-- foo                                                                                                                                                                                                            
|   |-- bar.py                                                                                                                                                                                                     
|   |-- foo.py                                                                                                                                                                                                     
|   |-- __init__.py                                                                                                                                                                                                
|   `-- module.py                                                                                                                                                                                                  
`-- test_package.py

How can I use absolute import in bar.py to import module.py? I tried from foo import module and import foo.module, but it always thinks the foo is from foo.py

Or I should always avoid having same name module file name as package name ?

foo.py

print 'you are in foo.py'

import foo
print 'foo', foo

bar.py

print 'you are in bar.py'

import foo
print 'foo from bar', foo

from foo import module
# import foo.module

test_package.py

import sys

sys.path.insert(0, '/home/user/tmp/testPath')

import foo.bar

but the error message is

you are in bar.py
you are in foo.py
foo <module 'foo.foo' from '/home/user/tmp/testPath/foo/foo.py'>
foo from bar <module 'foo.foo' from '/home/user/tmp/testPath/foo/foo.py'>
Traceback (most recent call last):
  File "/home/user/tmp/testPath/test_package.py", line 5, in <module>
    import foo.bar
  File "/home/user/tmp/testPath/foo/bar.py", line 8, in <module>
    from foo import module
ImportError: cannot import name module
Shuman
  • 3,914
  • 8
  • 42
  • 65

1 Answers1

1

In python 2, you have to enabled py3-style importing.

bar.py:

from __future__ import absolute_import
from foo import module

In python 3, everything should be normal already, but the future import will be working with no effect (i.e. not breaking the code).

This is the official documented and recommended way. It is recommended to have this future import (and few others) in every file in the project, just in case -- to make it more compatible with py3 from the beginning.

See also: https://www.python.org/dev/peps/pep-0328/

Sergey Vasilyev
  • 3,919
  • 3
  • 26
  • 37