How does importing work

Python noob here with a beginner question about importing modules:

What is the difference between

import somemodule

and

import somemodule as foo

Also, what about the dot? It implies a hierarchy.

For example I’ve seen this:

import seaborn.objects as so

If I already have this in my script:

import seaborn as sns

do I still need to import seaborn.objects, or was the contents already imported with the regular seaborn ?

Similarly, if I import chess, does that also automatically import every sub-thing (child module?), like chess.pgn and chess.engine?

Finally, I’ve also seen this:

from foo import bar

What is the significance of that, and is it related to the dot structure?

Thanks.

The only difference between these is that the second one changes the name you can access attributes under.

Both run the top-level code in the module if any (assuming it was the first time the module was imported in the program).

It first imports the package “seaborn” and then imports the sub-module “objects” from that and assigns the imported module object to the name so.

There is indeed a hierarchical relationship which is typically that seaborn is a folder with an __init__.py file alongside an “objects.py” file in this case.

Typically you need to import the sub-module explicitly as well but he package “seaborn” may have code that does it automatically for you if its always needed.

It may do so if the package is coded that way (and should typically be documented as such in that case). But if you don’t know you should do the imports explicitly before trying to use the submodules. Python will cache the result of an import anyway.

This is indeed more or less equivalent to

import foo.barfollowes by bar = foo.bar with the difference that you won’t also have foodefined in the global namespace in the former case.

3 Likes

Perfect. That concisely answered all of my questions. Thank you. :+1:

1 Like

so just to clarify … importing a sub-module automatically imports the parent module? In other words if I have

import seaborn.objects

then I do not also need to have

import seaborn

Before import the submodule, the parent module must be imported first.

Correct but I would expect most code to import the sub-module explicitly anyway if they use it for clarity.

It does have to be imported by python but that’s done automatically.

Your code doesn’t have to import the parent module first and can just import the sub-module directly.

2 Likes

5. The import system — Python 3.14.0 documentation