[英]Python override 3rd party package single file
What is the best way to override python any 3rd party package single file?覆盖 python 任何 3rd 方包单个文件的最佳方法是什么?
Suppose.认为。
I have a package called foo .我有一个名为foo的包。 Foo contains file tar.py which have an import line.
Foo 包含文件 tar.py,其中有一个导入行。
tar.py tar.py
from xyz import abc
# some code
how do I replace that single line import我如何替换单行导入
# from
from xyz import abc
# to
from xyz.xy import abc
i want to change this line outside virtualenv in python project我想在 python 项目中的 virtualenv 之外更改这一行
You can override builtins.__import__
with a wrapper function that changes the package name to 'xyz.xy'
if it is equal to 'xyz'
:您可以使用包装函数覆盖
builtins.__import__
,如果它等于'xyz'
,该函数将包名称更改为'xyz.xy'
'xyz'
:
def my_import(name, *args, **kwargs):
if name == 'xyz':
name = 'xyz.xy'
return original_import(name, *args, **kwargs)
import builtins
original_import = __import__
builtins.__import__ = my_import
from foo import tar
Demo: https://repl.it/@blhsing/ComplicatedGrandUnits演示: https : //repl.it/@blhsing/ComplicatedGrandUnits
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.