My directory structure is:
./
├── foo
│ ├── bar.py
│ ├── foo.py
│ └── __init__.py
└── main.py
with:
bar.py:
def get_data():
return 'ha'
foo.py:
class foo:
def __init__(self):
self.lib = __import__('bar', fromlist=['bar'])
self.data = self.lib.get_data()
def print_data(self):
print(self.data)
if __name__=='__main__':
f = foo()
f.print_data()
__init__
.py:
from foo import foo
and main.py:
from foo import foo
a = foo()
a.print_data()
Running python foo.py
I get ha
correctly, but running python main.py
I get the following message:
Traceback (most recent call last):
File "main.py", line 3, in <module>
a = foo()
File ".../foo/foo.py", line 3, in __init__
self.lib = __import__('bar')
ImportError: No module named bar
My requirements are 1) making foo
to work like a package, 2) using __import__
in foo.py
's __init__
function instead of import
in the first line of foo.py
.
I changed line 3 of foo.py
to self.lib = __import__('foo.bar', fromlist=['bar'])
, and then got the correct answer. But that is not I want, since running python foo.py
will lead to a failure and that is not a package solution when the whole directory ./
become another package. It seems an import path problem that I cannot figure out.