Lazy Imports: The Key To Optimizing Python Script Performance?

preview_player
Показать описание
In many programming languages, the concept of lazy loading is quite popular. You experience lazy loading on a daily basis, even on YouTube for example. When you make a search it will load around 10-20 results at a time, instead of loading all 10 million of them, because it's faster and more efficient.

Lazy imports work somewhat in the same way, you only load the functionality you need, when you actually use it. Although it does come at the cost of having to load those resources later, which could hurt the performance of your app in some situations.

▶ Become job-ready with Python:

▶ Follow me on Instagram:

00:00 Intro
00:22 Getting started
01:03 Getting the memory usage
01:47 Lazy import class
04:02 main()
06:55 Using a lazy import
08:01 Pros & cons
10:44 Conclusion
Рекомендации по теме
Комментарии
Автор

My version of "lazy imports" was placing the import function inside of a definition. Love learning the correct way and appreciate the vid!

ryanjohanides
Автор

When you’re making tutorials for others to learn from, you may want to think about using a font without coding ligatures. It can be difficult for those unfamiliar with the symbols to know what combination of characters created some of the ligatures. ❤

RedBearAK
Автор

1) According to PEPs, you really want to have all the imports in the script header.
2) You never can "unload" the module, so the one you loaded will take memory forever.

The code you write is essentially equivalent to
if 'pi' in msg: import numpy
This pactice is quite discouraged, at least for not-so-big applications.

shipilode
Автор

Thank you. This is probably one of the best explanations I've heard on this subject.

sto
Автор

Amazing video as always learned a lot 👍🏻🔥

dk-wwkp
Автор

We could also implement this in a sys.meta_path finder so we could use the `import` keyword for lazy imports, but the problem with this is that we will no able to load modules until we access their attributes, this could be solved if we add a magic module in the finder:

import load.numpy as np

Or alternatively we could create a magic module with `lazy`

import lazy.numpy as np

That looks cool for me, i think it would be good as part of the standard library or as a pip library

gabi_kun
Автор

So why can’t you just put your import statement right before you need numpy? I recreated your example using this approach and got the same results that you did.

thatsunpossible
Автор

I don't understand single word. Where should I start learning

y.
visit shbcf.ru