简体   繁体   中英

Overriding module function after it is imported - Python

Let's say we have three python modules: app.py, commons.py and c.py

commons.py:

def func():
    pass

def init(app)
    global func
    func = app.func

app.py:

import commons
import c
# Doing some initialization so that we are ready to override the function
c.foo()
init(app) # the app object contains a function called func which we wish to overwrite in commons.py
c.foo()

c.py:

from commons import *
def foo():
    func()

What i want to accomplish is that the first time c.foo is called, it will do nothing, and the second time it will execute app.func. Every module in my project is dependent on the func in commons.py, and the function has to be declared at runtime as it is attached to an object.

Is there a way to import by reference in python and change the pointer of the function in all modules?

What I've done so far is to have an init function in every module and simply overwrite empty lambda functions, but this seems to be a poor solution.

You can achieve this with a further level of indirection:

commons.py

def normalFunc():
    pass
def func():
    normalFunc()

def init(app)
    global normalFunc
    normalFunc = app.func

This works, because any other module which has the normal: from commons import foo and foo() still calls the same foo() .

Its just that the internals of foo() change each time that the init() function is called.

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