开发者

NameError in defining python multi-level package

I'm trying to create a simple multi-level package:

test_levels.py
level1/
        __init__.py (empty file)
        level2/
                __init__.py  (only contents: __all__ = ["leaf"])
                leaf.py

leaf.py:

class Leaf(object):
    print("read Leaf class")
    pass

if __name__ == "__main__":
    x = Leaf()
    print("done")

test_levels.py:

from level1.level2 import *
x = Leaf()

Running leaf.py directly works fine, but running test_levels.py returns the output below, where I was expecting no output:

rea开发者_如何转开发d Leaf class
Traceback (most recent call last):
  File "C:\Dev\intranet\test_levels.py", line 2, in <module>
    x = Leaf()
NameError: name 'Leaf' is not defined

Can someone point out what I'm doing wrong?


try to add

from leaf import *

in file level1/level2/__init__.py

upd: as in previous comment, add dot before module name, and remove "__all__" declaration.

$ cat level1/level2/__init__.py
from .leaf import Leaf
$ cat level1/level2/leaf.py
class Leaf:
    def __init__(self):
        print("hello")
$ cat test.py
from level1.level2 import *
x = Leaf()
$ python test.py
hello


In level1/level2/__init__.py, I think you want to do from leaf import * (or, in Py3k, from .leaf import *).

When you import from level1.level2, you're really importing the __init__.py file in that directory. Since you haven't defined Leaf in there, you don't get it by importing that.


Are you expecting to import all the variable names from all the modules in that package? That's a horrible idea. To do what you want, it should be

from level1.level2.leaf import *

or even better yet to remove the wildcard import, which is usually bad, it should be

from level1.level2.leaf import Leaf
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜