我想装饰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