简体   繁体   English

模块同名时导入python包

[英]import python package when module is same name

I have a module blah.time where I do some sanity checks and wrapper functions around normal time and date operations: 我有一个模块blah.time ,我在正常的时间和日期操作周围进行一些健全性检查和包装函数:

import time

def sleep(n):
    time.sleep(n)

When I call sleep , it just throws a maximum recursion error. 当我调用sleep ,它只会抛出一个最大的递归错误。 I'm guessing the namespace is wrong, so I tried using import time as _time , but I still get the same error. 我猜测命名空间是错误的,所以我尝试使用import time as _time ,但我仍然得到相同的错误。

How do I reference the system time module from within my own module in order to prevent this namespace conflict? 如何从我自己的模块中引用系统time模块以防止此命名空间冲突?

Add from __future__ import absolute_import as the first line in your file. from __future__ import absolute_import添加为文件的第一行。

This will force all imports to be absolute rather then relative. 这将强制所有进口绝对而不是相对。 So import time will import the standard module, to import a local module you'd use from . import foobar 因此import time将导入标准模块,以导入您使用的本地模块from . import foobar from . import foobar

I would read http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports and then use from __future__ import absolute_import . 我会阅读http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports ,然后使用from __future__ import absolute_import

HTH HTH

What's happening is that your time module is shadowing the system time module. 发生的事情是您的time模块正在影响系统time模块。 The easiest way around the problem is to rename your module to something besides time . 解决问题最简单的方法是将模块重命名为time之外的某些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM