Python: How to import a package twice?

Is there a way to import a package twice into the same python session under the same name, but in different areas, in a multi-threaded environment?

I would like to import a package and then redefine some of its functions so that it changes its behavior only when used in a specific class.

For example, is it possible to achieve something similar?

import mod

class MyClass:

  mod = __import__('mod')

  def __init__():
     mod.function = new_function # override module function

  def method():
     mod.function() # call new_function

mod.function() # call original function

This may seem strange, but in this case, the user receiving the class will not have to change their code in order to use the improved package.

+4
source share
2 answers

It looks like a job for the context manager.

import modul

def newfunc():
    print('newfunc')

class MyClass:
    def __enter__(self):
        self._f = modul.func
        modul.func = newfunc
        return self

    def __exit__(self, type, value, tb):
        modul.func = self._f

    def method(self):
        modul.func()


modul.func()
with MyClass() as obj:
    obj.method()
    modul.func()
modul.func()

exits

func
newfunc
newfunc
func

where modul.pycontains

def func():
    print('func')

. ( OP)

+1

:

def freshimport(name):
    import sys, importlib
    if name in sys.modules:
        del sys.modules[name]
    mod = importlib.import_module(name)
    sys.modules[name] = mod
    return mod

:

import mymodule as m1
m2 = freshimport('mymodule')
assert m1.func is not m2.func

importlib.reload , "" :

import importlib
import mymodule as m1
print(id(m1.func))
m2 = importlib.reload(m1)
print(id(m1.func))
print(id(m2.func))

:

139681606300944
139681606050680
139681606050680
+1

Source: https://habr.com/ru/post/1608128/


All Articles