6) Advanced Python Concepts Lesson

Python Import Namespaces

3 min to complete · By Martin Breuss

Python: Import Namespaces

In the previous lesson, you learned that you could import your own code in the same way that you can import modules from the standard library, as well as external packages that you've installed with pip.

But what if your code is nested in additional folders:

codingnomads
├── ingredients.py
├── recipes
│   └── soup.py
└── cook.py

How can you access the logic you wrote in soup.py from your cook.py script?

Deeper Namespaces

In a similar way to how you've used a namespace before with the ingredients.py script, you can do it with your recipes/soup.py file as well:

# cook.py
import ingredients as i
import recipes.soup as s

c = i.carrot
s.make_soup(c)

In this example, you can see that Python treats the additional folder as an extra namespace. Depending on how you choose to import your code, you can access it through the full namespace, recipes.soup, or through an alias, as shown in the code snippet above.

Colorful illustration of a light bulb

Note: For the code snippet to work, you need to have both a carrot variable defined in ingredients.py, as well as a make_soup() function in recipes/soup.py that takes one argument. You can only import and use what you've actually defined.

Python allows you to handle namespaces in a way that can seem intuitive when you're used to working with folder structures.

In a future lesson, you'll run into a little side-effect that you might encounter when you're importing code from your custom modules.