I have a python module_A
which is doing something like this:
myvar = "Hello"
def message():
print myvar
From another module, I want to import the function message
:
from module_A import message
But this is defining myvar
, which I do not want (for reasons not really relevant here). I guess what I need is to make a distinction between importing things from a module, and using any of the imported symbols. I actually want myvar
to be initialized only when I use message
.
I there any kind of python hook that I could use to initialize stuff whenever a function or class is accessed? I would like something similar to the following:
module_setup_done = False
def setup():
global module_setup_done, myvar
if not module_setup_done:
myvar = "Hello"
module_setup_done = True
def message():
setup()
print myvar
But, to reduce clutter, I would like this to be called automatically, something like this:
def _init_module():
global myvar
myvar = "Hello"
def message():
print myvar
Where _init_module()
would be called only once, and only the first time that something in the module is accessed, not when something is imported.
Is there support for this kind of pattern in python?