Keep a function dynamically added to a module when creating a new module from the spec of the first one

Viewed 24

I have a Python module to which I dynamically add a function. When I import this module in my code, this function is actually present in my module (because the module when firstly import was cached in sys.modules).
I have a library that get the spec of my module to create a new module from it. But this new module doesn't have my new function when I want him to have it too. Here is a simplified example of my situation.

The module test:

def fun1():
    pass

And the main code:

import importlib.util
import inspect
import sys

def fun2():
    print("It's Work!")

module = importlib.import_module('test')
print(dir(module))
module.fun2 = fun2

module2 = importlib.import_module('test')
print(dir(module2)) # fun2 is present even if I reimport the module

# ---- Managed by the library so I can't modify the following code ----

spec = module.__spec__
lib = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lib)

# ---------------------------------------------------------------------

print(dir(lib)) # fun2 is absent

The line spec.loader.exec_module(lib) loads all functions from the spec of my first module and my function fun1 is present in the lib after that unline fun2.

How can I persist the dynamic function fun2?
Thanks!

0 Answers
Related