Python拉皮条/猴子补丁



我想做一件简单的事情:monkey补丁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)

This is on a file called datetime.py inside a package I called pimp.

From the error message I'm given:

Traceback (most recent call last):
  File "run.py", line 1, in 
    from pimp.datetime import datetime
  File "/home/lg/src/project/library/pimp/datetime/datetime.py", line 1, in 
    from datetime import datetime as _datetime
ImportError: cannot import name datetime

I assume that I can't have a module called datetime importing anything from another module called datetime.

How should I proceed to keep my module and class named datetime?

Put you module into a package e.g., your_lib.datetime. You should not use datetime name for a top-level module.

If you are on Python 2 then add at the top:

from __future__ import absolute_import

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

your_lib/
├── datetime.py
└── __init__.py

以下命令有效:

$ python -c 'import your_lib.datetime'

其中datetime.py为:

from __future__ import absolute_import
from datetime import timedelta

相关内容

  • 没有找到相关文章

最新更新