简体   繁体   中英

Python override 3rd party package single file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM