与现有模块同名的python模块名称 [英] python module names with same name as existing modules

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

问题描述

我在"msa"命名空间下组织了许多小型utils模块,因此我可以在许多不同的研究项目中使用.目前,我将它们组织成这样:

I have a number of small utils modules that i organize under a 'msa' namespace so I can use in a number of different research projects. Currently I have them organized like this:

# folder structure:
packages  <-- in my pythonpath
--msa
----msa_utils.py
----msa_geom.py
----msa_pyglet.py
----msa_math.py
----etc

# imported and used this like
from msa import msa_pyglet
from msa import msa_math
msa_pyglet.draw_rect(msa_math.lerp(...))

但是我想避免在名称中使用'msa_'并这样使用:

However I would like to avoid the 'msa_' in the names and use like this:

# folder structure:
packages  <-- in my pythonpath
--msa
----utils.py
----geom.py
----pyglet.py
----math.py
----etc

# imported and used this like
import msa.pyglet
import msa.math
msa.pyglet.draw_rect(msa.math.lerp(...))

从外部导入时,这不会引起名称冲突,但是,当模块本身导入名称冲突的模块时,就会发生名称冲突.例如. msa/pyglet需要导入pyglet(外部的),但最终尝试导入自身.同样,任何尝试导入标准数学库的模块都只会导入我的数学模块.这都是可以理解的.但是,处理这种问题的常用pythonic方法是什么?我必须给每个模块文件一个全局唯一的名称吗?

This shouldn't cause name conflicts when importing from outside, however there are name conflicts when the modules themselves import modules with conflicting names. E.g. msa/pyglet needs to imports pyglet (the external one), but ends up trying to import itself. Likewise any module which tries to import the standard math library imports only my math module. Which is all understandable. But what is the usual pythonic way of dealing with this? Do I have to give each module file a globally unique name?

推荐答案

在Python 2中,确实在没有包限定符的情况下导入包时,首先会寻找 package local 模块.

In Python 2, imports in packages without a package qualifier indeed first look for package local modules.

因此,import pyglet将在考虑顶级pyglet之前找到msa.pyglet.

Thus, import pyglet will find msa.pyglet before the top-level pyglet is considered.

切换为绝对导入以使Python 3行为成为默认行为,其中不合格的名称始终为顶级名称:

Switch to absolute imports to make the Python 3 behaviour the default, where unqualified names are always top level names:

from __future__ import absolute_import

现在,import pyglet只能找到顶级名称,而永远找不到msa.pyglet.要引用msa名称空间中的其他模块,请使用from . import pygletfrom msa import pyglet.

Now import pyglet can only ever find the top-level name, never msa.pyglet. To reference other modules within your msa namespace, use from . import pyglet or from msa import pyglet.

请参见 PEP 328-导入:多行和绝对/相对 以获得更多详细信息.

See PEP 328 -- Imports: Multi-Line and Absolute/Relative for more details.

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

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