不能用我自己的时间模块来隐藏python时间模块

2024-04-19 11:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含三个文件的文件夹:

  • 你知道吗测试.py你知道吗
  • 你知道吗时间.py你知道吗
  • 你知道吗日期时间.py你知道吗

你知道吗时间.py以及日期时间.py完全相同:

def ticks_ms():
    return 5

什么时候测试.py看起来像这样:

import datetime as t
print(t.ticks_ms())

打印5张。如果我把它改成:

import time as t
print(t.ticks_ms())

我得到:

AttributeError: module 'time' has no attribute 'ticks_ms'

为什么我可以隐藏datetime模块而不是time模块?你知道吗


Tags: 模块文件pyimport文件夹datetimereturntime
1条回答
网友
1楼 · 发布于 2024-04-19 11:19:29

Why can I shadow the datetime module but not the time module?

因为Python将首先搜索内置模块(用C实现),然后再搜索普通的.py文件(在不同的位置,从cwd开始,请参阅sys.path的内容)。你知道吗

您可以通过检查sys.meta_path看到这一点,其中包含在发生模块导入时查询的查找器(在sys.modules中找不到的模块):

>>> sys.meta_path
[<class '_frozen_importlib.BuiltinImporter'>, 
 <class '_frozen_importlib.FrozenImporter'>, 
 <class '_frozen_importlib_external.PathFinder'>]

这个列表中的第一个是BuiltinImporter,顾名思义,它负责查找内置模块。你知道吗

时间模块是内置的(请参见sys.builtin_module_names了解这些模块的列表):

>>> time
<module 'time' (built-in)>

在执行time.py搜索之前找到。而datetime.py不是:

>>> datetime
<module 'datetime' from '/home/jim/anaconda3/lib/python3.6/datetime.py'>

因此当前工作目录中的datetime.py会屏蔽它(PathFinder通过查看sys.path中列出的条目来查找datetime.py)。你知道吗


是的,您可以重新排序sys.meta_path中的查找程序,并将PathFinder放在第一位,从而导致time.py被找到,但请不要这样做(除非您只是在试验:-)。你知道吗

相关问题 更多 >