0

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.

matsjoyce
  • 5,744
  • 6
  • 31
  • 38

1 Answers1

0

Changing foo.py to that makes it work correctly:

import importlib


class foo:
    def __init__(self):
        self.lib = importlib.import_module('foo.bar')
        self.data = self.lib.get_data()

    def print_data(self):
        print(self.data)

if __name__=='__main__':
    f = foo()
    f.print_data()
Gill Bates
  • 14,330
  • 23
  • 70
  • 138
  • Thanks. But it is like the solution in my last paragrah in the question. It works right only for `python main.py`. – Taz'dingo Dec 17 '14 at 14:38
  • @Taz'dingo Oh, sorry, I see. I think you cant avoid the error, because imports in python are not relative to directory structure, they relative to `__main__` module. – Gill Bates Dec 17 '14 at 14:53
  • [link](http://stackoverflow.com/questions/2724260/why-does-pythons-import-require-fromlist) makes me think that `import bar`(common import way in first line of the `.py` script) is implemented by `__import__()`, and `import bar` with `self.data = bar.get_data()` can solve the problem. That's why I think my requirements have a solution. – Taz'dingo Dec 17 '14 at 15:46