Python: what does “import” prefer - modules or packages?

后端 未结 2 1816
你的背包
你的背包 2021-01-17 09:59

Suppose in the current directory there is a file named somecode.py, and a directory named somecode which contains an __init__.py file.

2条回答
  •  旧巷少年郎
    2021-01-17 10:34

    Packages will be imported before modules. Illustrated:

    % tree .
    .
    |-- foo
    |   |-- __init__.py
    |   `-- __init__.pyc
    `-- foo.py
    

    foo.py:

    % cat foo.py 
    print 'you have imported foo.py'
    

    foo/__init__.py:

    % cat foo/__init__.py
    print 'you have imported foo/__init__.py'
    

    And from interactive interpreter:

    >>> import foo
    you have imported foo/__init__.py
    

    I have no idea where this is officially documented.

    Edit per comment: This was performed with Python 2.7 on Mac OS X 10.6.7. I also performed this using Python 2.6.5 on Ubuntu 10.10 and experienced the same result.

提交回复
热议问题