I am writing a module that provides one function and needs an initialization step, however due to certain restrictions I need to initialize on first call, so I am looking for the proper idiom in python that would allow me to get rid of the conditional.
#with conditional
module.py
initialized = False
def function(*args):
if not initialized: initialize()
do_the_thing(*args)
I’d like to get rid of that conditional with something like this(it does not work):
#with no conditional
module.py
def function(*args):
initialize()
do_the_thing(*args)
function = do_the_thing
I realize that I cannot just use names in the module and change them at runtime because modules using from module import function will never be affected with a function=other_fun inside the module.
So, is there any pythonic idiom that could do this the right way?
The nothing-fancy way (of the methods I post here, this is probably the best way to do it):
module.py:
The idea is simple: you just add a layer of indirection.
functionalways calls_function, but_functionpoints first atfirsttime, then forever after atdo_the_thing.test.py:
Running test.py yields
My first thought was to use a generator, but, as Triptych points out, there is no way to pass args to the function if you use a generator. So…
here is a way using a coroutine (which, unlike a generator, allows you to send args to — as well as receive values from — the coroutine):
module.py:
Running
yields