简体   繁体   English

无意中覆盖了Python 2.7标准模块 - 如何防范?

[英]Unintentionally overwriting Python 2.7 standard module - how to prevent?

I wanted to add some stuff to Python's logging module, so I created a separate module under package name "my", which is inside the project's directory (which is the first entry in sys.path ). 我想在Python的日志记录模块中添加一些东西,所以我在包名“my”下创建了一个单独的模块,它位于项目目录中(这是sys.path的第一个条目)。 I also have another module of mine, which lives in that same space: 我还有另一个模块,它位于同一个空间:

my
my.logging
my.something

Now I wanted to log stuff in my.something and added import logging to the file - but it seems Python loads my.logging instead of the standard module. 现在,我想在my.something记录内容,并将import logging添加到文件中-但似乎Python会加载my.logging而不是标准模块。

When reading the Python documentation (section 6.1.2. The Module Search Path), I thought I was safe: 阅读Python文档(第6.1.2节“模块搜索路径”)时,我认为我很安全:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. 导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。 If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. 如果未找到,则会在变量sys.path给出的目录列表中搜索名为spam.py的文件。

So a "standard module" is not a "built-in module"? 那么“标准模块”不是“内置模块”吗? I guess then, that I have to move the my modules out of the current directory - ? 我想那时,我必须将my模块移出当前目录 - ? Other possibilities? 其他可能性?

When it says "built-in module", that line of docs is referring to modules actually compiled directly into the Python executable. 当它说“内置模块”时,那行文档指的是实际直接编译到Python可执行文件中的模块。 You can see which ones those are in sys.builtin_module_names . 你可以看到sys.builtin_module_names的那些。

What you need to do is turn off implicit relative imports, which can be done on a per-file basis with the absolute_import future statement: 您需要做的是关闭隐式相对导入,这可以使用absolute_import future语句在每个文件的基础上完成:

from __future__ import absolute_import

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

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