user3532232
user3532232

Reputation: 257

Python: Lazy import of modules

I earlier researched lazy import of modules and found this way of doing it:

def some_funk():
    lazy_module = __import__("lazy_module")
    lazy_obj = lazy_module.LazyClass()
    lazy_obj.do_stuff()

Then I've seen some examples simply using:

def some_funk()
    import lazy_module
    lazy_obj = lazy_module.LazyClass()
    lazy_obj.do_stuff()

I prefer the later use and will rewrite my code to this.

But my question is if there is any difference between the two ways of doing lazy imports

Upvotes: 0

Views: 1021

Answers (1)

Pablo
Pablo

Reputation: 446

You might want to check the documentation for import out. import lazy_module is internally calling __import__("lazy_module").

The lazy part of the import comes from both of them being done in a function, and not in the top of the class/script.

Upvotes: 4

Related Questions