【发布时间】:2014-05-25 07:56:13
【问题描述】:
以下哪些 Python 2.7 导入场景是正确的?即,如果我有一个名称隐藏 stdlib 模块的模块,应该 import <module> 导入 stdlib 还是本地版本?
在 Linux 上
$ ls
__init__.py time.py
~/tmp $ cat time.py
def a():
print(¨a¨)
~/tmp $ python
Python 2.7.4 (default, Sep 26 2013, 03:20:26)
[GCC 4.7.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> dir(time)
['__doc__', '__name__', '__package__', 'accept2dyear', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'gmtime', 'localtime', 'mktime', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname', 'tzset']
在 OSX 上
sdk$ ls
__init__.py time.py time.pyc
$ cat time.py
def a():
print("a")
$ python
Python 2.7.6 (default, Apr 9 2014, 11:48:52)
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> dir(time)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'a']
PS:Windows 似乎跟随 Linux 并且使用 __future__ import absolute_import 没有效果
【问题讨论】:
-
您确定两个操作系统都将您的模块包含在 python 路径中吗?
-
在第一个示例中您不是 cd 到
~/tmp吗?那里有__init__.py吗? -
为什么要使用同名模块?
-
@PadraicCunningham 我认为问题的重点是,两个同名模块中的哪一个将/应该被选中。不幸的是,似乎在不同的目录中运行
ls和python会混淆这个问题。 -
在复制和粘贴中遗漏了一点。
ls和python都从同一目录tmp运行,否则cat将无法工作。