Reputation: 1675
def my_func(text):
import my_module
return my_module.compute(text)
I run my program and it seems it's fine. I am afraid the class in my_module may be initialized multiple times for each, but the logging message in the initializer shows it is only initialized once.
Is this a good way for lazy initialization?
Upvotes: 0
Views: 55
Reputation:
Don't see anything strange in it:
import sys
def func(v):
from math import sqrt
return sqrt(v)
def main():
for i in range(1000):
func(i * i)
print([m for m in sys.modules.keys()].\
count("math"))
if __name__ == "__main__":
main()
Output:
1
What profiler says:
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 0.003 0.003 temp.py:2(<module>)
These are cProfile feature. Nonetheless, sqrt
is imported exactly once.
Upvotes: 1
Reputation: 77347
This is a good way to do lazy initialization. Python only imports a module once. After that its in sys.modules
and the check to see if the module is loaded is fast.
If the module is always imported, put it at the top of the module. If the importing function is called extremely often then there may be a call to do it outside of the function.
Upvotes: 0
Reputation: 1170
Its generally considered good practice to import all modules at the very beginning of the program. It's best to do this as it not only keeps all the modules together and looking cleaner, but it also allows you to access classes and methods inside of that python module elsewhere in your program, rather than just in that function's scope.
Upvotes: 1