Python拉皮条/猴子补丁

Luí*_*rme 5 python datetime python-import

我想做一件简单的事情:monkey-patch datetime。我不能完全那样做,因为datetime是 C 类。

所以我写了下面的代码:


from datetime import datetime as _datetime

class datetime(_datetime): def withTimeAtMidnight(self): return self.replace(hour=0, minute=0, second=0, microsecond=0)

这是在我称为 pimp 的包中名为 datetime.py 的文件中。

从我得到的错误消息中:

回溯(最近一次调用最后一次):
  文件“run.py”,第 1 行,在 
    从 pimp.datetime 导入日期时间
  文件“/home/lg/src/project/library/pimp/datetime/datetime.py”,第 1 行,在 
    从日期时间导入日期时间为 _datetime
导入错误:无法导入名称日期时间

我假设我不能有一个名为datetime从另一个名为datetime.

我应该如何继续保持我的模块和类的命名datetime

jfs*_*jfs 4

将模块放入包中,例如your_lib.datetime. 您不应该使用datetime顶级模块的名称。

\n\n

如果您使用的是 Python 2,请在顶部添加:

\n\n
from __future__ import absolute_import\n
Run Code Online (Sandbox Code Playgroud)\n\n

禁止包内隐式相对导入。那么如果你的目录结构是:

\n\n
your_lib/\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 datetime.py\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 __init__.py\n
Run Code Online (Sandbox Code Playgroud)\n\n

以下命令有效:

\n\n
$ python -c 'import your_lib.datetime'\n
Run Code Online (Sandbox Code Playgroud)\n\n

哪里datetime.py

\n\n
from __future__ import absolute_import\nfrom datetime import timedelta\n
Run Code Online (Sandbox Code Playgroud)\n