gpt4 book ai didi

python - 覆盖 `from my_module import ...`

转载 作者:行者123 更新时间:2023-12-01 09:17:46 26 4
gpt4 key购买 nike

我正在尝试让以下行为发挥作用:

from my_module import some_random_string

我的模块应该拦截它并根据some_random_string返回某些值。

我尝试设置导入 Hook ,但它没有按预期工作:

# custom_import.py
import sys

class MyImporter(object):
def find_module(self, filename, path):
print(filename, path)
return "foobar"

def load_module(self, module_name):
print(module_name)
return "foobar"

sys.meta_path.append(MyImporter())
# interactive console
>>> from custom_import import some_string
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name some_string
>>>

为什么会这样以及如何解决这个问题?

最佳答案

能够导入 my_module 中不存在的任何对象(假设my_module存在并且可访问)我们可以从简单的包装my_module开始喜欢

import importlib
import sys
import types


class ModuleWrapper:
def __init__(self, module):
self.module = module

@property
def __path__(self):
return None

def __getattr__(self, name):
try:
return getattr(self.module, name)
except AttributeError:
# returning `module` object is not necessary,
# can be something else
return types.ModuleType(name)


my_module = importlib.import_module('my_module')
sys.modules['my_module'] = ModuleWrapper(my_module)

测试

具有项目结构

my_module.py

test.py

及内容

  • my_module.py:

    ...snippet above...
    some_name = 'Sample text'
  • test.py:

    from my_module import some_name, z

    print(some_name)
    print(z)

执行中

> python test.py

给我们提供Python2.7.0

Sample text
<module 'z' (built-in)>

以及Python3.5.4

Sample text
<module 'z'>

关于python - 覆盖 `from my_module import ...`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51087634/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com