What happens when you import a module?
2022-07-13 , The Auditorium

It's a rare program that doesn't include at least one "import" statement. But what actually happens when we import a module? How does Python find our file, decide whether to load it, and then keep track of it in memory? In this talk, I'll walk you through what happens when you "import" a module into Python, revealing the complexities of something seemingly simple that we use every day.


Modules are a key feature of Python, allowing us to easily reuse our own code and take advantage of publicly available modules from PyPI. It's a rare program that doesn't include at least one "import" statement. But what actually happens when we import a module? How does Python find our file? How does it decide whether it should even try to find our module? And after it finds our module file, how does Python load it into memory, assigning to its attributes?

In this talk, I'll walk you through what happens when you "import" a module into Python. The mechanism is surprisingly complex, in no small part because it has to take so many possibilities into consideration. We'll talk about finders and loaders, and about the many ways in which you can customize the module-loading mechanism if you find a need to do so.

If you've ever imported a module, then this talk will pull back the curtain a bit, helping you to understand what's happening under the hood.


Expected audience expertise: Domain:

none

Expected audience expertise: Python:

some

Abstract as a tweet:

What happens when you import a module in Python? Let's pull back the curtain and find out!

Reuven is a full-time trainer in Python and data science, teaching companies around the world via in-person, online, and recorded courses. He is the author of both "Python Workout" and "Pandas Workout," published by Manning, and writes the free, weekly "Better developers" newsletter read by more than 25,000 developers around the world. He lives with his wife and children in Modi'in, Israel.