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?
1 Answer 1
No, there is no built-in support for this. If you want to initialize things separately from importing the module, write a function that does that initialization, then call the function when you want to initialize those things. If you want to "automatically" initialize things when other things are called, you have to handle that yourself with code along the lines of what you already posted.
If you find yourself doing that, though, you're probably doing something unpythonic. You don't give details about why you're doing it here, but in general this sort of implicit initialization is not a good practice in Python. Things are initialized when you explicitly tell them to be, for instance by importing a module or calling some sort of initialization function. Why do you feel the need to have this separate, implicit initialization step?