Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 850
rahul.m Avatar asked Dec 26 '19 07:12

rahul.m


1 Answers

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

like image 162
blhsing Avatar answered Sep 19 '22 16:09

blhsing