将修饰的模块作为原始名称导入,而无需更改代码即可导入

时间:2019-02-17 01:06:03

标签: python import decorator

我想装饰pandas.DataFrame.to_csv模块, 但不想修改导入熊猫的代码。

以下是我尝试过但没有起作用的

main.py

import pandas
pandas.DataFrame.to_csv(DATAFLAME_INSTANCE)

添加在__init__.py之后放置的python路径
export PYTHONPATH="/mylib"

/mylib/pandas/__init__.py

import sys
syspath = sys.path
# remove added lib path so that "import" imports original pandas
syspath_list = list(syspath)
syspath_list.remove("/mylib")
sys.path = tuple(syspath_list)
from pandas import *
from pandas import DataFrame as _DataFrame
# restore sys.path so that main.py read this __init__.py
sys.path = syspath

class DataFrame(_DataFrame):
    def to_csv(self, *args, **kwargs):
        print("decorated")
        super(_DataFrame, self).to_csv(*args, **kwargs)

执行main.py时会发生此错误

$ python main.py
(general) PC:sacred-test user$ python main.py 
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import pandas
  File "/mylib/pandas/__init__.py", line 8, in <module>
    from pandas import DataFrame as _DataFrame
ImportError: cannot import name 'DataFrame'

在此示例中,我希望main.py生成“装饰”标准输出 最终,我发现我不必使用@deco

0 个答案:

没有答案