当模块名称相同时,导入python包 [英] import python package when module is same name

查看:80
本文介绍了当模块名称相同时,导入python包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个模块blah.time,我在其中进行一些正常时间和日期操作的健全性检查和包装器功能:

I have a module blah.time where I do some sanity checks and wrapper functions around normal time and date operations:

import time

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

当我调用sleep时,它只会引发最大的递归错误.我猜想名称空间是错误的,所以我尝试使用import time as _time,但仍然遇到相同的错误.

When I call sleep, it just throws a maximum recursion error. I'm guessing the namespace is wrong, so I tried using import time as _time, but I still get the same error.

如何从我自己的模块中引用系统time模块,以防止此命名空间冲突?

How do I reference the system time module from within my own module in order to prevent this namespace conflict?

推荐答案

在文件的第一行添加from __future__ import absolute_import.

这将强制所有导入为绝对导入,而不是相对导入.因此,import time将导入标准模块,以导入要使用from . import foobar

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

这篇关于当模块名称相同时,导入python包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆