Python Forum

Full Version: [newbie] Why is a module imported twice?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

In this example, I notice the module is imported twice.

import gpxpy
import gpxpy.gpx
I assume it's a way to save some typing by pointing directly to some sub-module. Is that right?

Thank you.
I think gpxpy is the module of code and .gpx is a file type
Fidgety - no.

See the documentation at Python docs Look particularly at part 5.2 and onward.

There are a variety of reasons for importing submodules separately, and while yes it can help shorten typing (and perhaps a bit of execution time) esp if you use something like import matplotlib.pyplot as plt

a bigger difference is that the import of each submodule executes that submodule's __init__.py
I don't know that I agree with this:
Quote:a bigger difference is that the import of each submodule executes that submodule's __init__.py
This would be true if each submodule was in a subdirectory of the package, but that doesn't have to be true for submodules.

Take tkinter for example. All the submodules are .py files in the PythonXX\Lib\tkinter folder. import tkinter.ttk imports the ttk module. It would also execute the __init__.py in that folder. However, most programs import tkinter and then tkinter.ttk, so the __init__.py file is already executed by the time we get around to importing ttk. So what you say could be true, but it could also be false.

I was surprised to find out I can do this:
import tkinter.ttk

x = tkinter.Tk()
tkinter.Label(x, text="This is a long label").pack()
tkinter.Label(x, text="This is a long label").pack()
tkinter.Label(x, text="This is a long label").pack()
x.mainloop()
In this example the import tkinter.ttk does execute tkinter.__init__.py, and all the tkinter symbols are added to the namespace.