What is the best way to override python any 3rd party package single file?
Suppose.
I have a package called foo. Foo contains file tar.py which have an import line.
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
You can override builtins.__import__
with a wrapper function that changes the package name to 'xyz.xy'
if it is equal to '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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With