开发者

Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.__init__ is not completed?

开发者 https://www.devze.com 2023-03-13 21:10 出处:网络
Why is there a difference between \'import ...\' and \'from ... import ...\' and why do I get an exception using the first one?

Why is there a difference between 'import ...' and 'from ... import ...' and why do I get an exception using the first one?

Here is my layout:

/tmp/zero/
|~two/
| |-__init__.py
| |-four.py
| `-three.py
|-__init__.py
`-one.py


/tmp/zero/one.py
=================
import zero.two

    /tmp/zero/two/__init__.py
    =================
    import zero.two.three

    /tmp/zero/two/three.py
    =================
    # this works
    from zero.two import four
    four.myprint()

    # this FAILS
    import zero.two.four
    zero.two.four.myprint()

    /tmp/zero/two/four.py
    =================
    def myprint():
        print 'four.myprint'

/tmp$ PYTHONPATH=/tmp/ py开发者_如何学Cthon -c 'import zero.one'
four.myprint
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "zero/one.py", line 1, in <module>
    import zero.two
  File "zero/two/__init__.py", line 1, in <module>
    import zero.two.three
  File "zero/two/three.py", line 9, in <module>
    zero.two.four.myprint()
AttributeError: 'module' object has no attribute 'two'


zero.two is a module there, zero/two/__init__.py. It's a concrete thing, not a magic thing. If you put into zero/two/__init__.py a line from . import four, it'll start working. os.path is an example of this - it's a module, but it's imported in os/__init__.py so that you can import os; os.path.

0

精彩评论

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

关注公众号