Reputation: 1114
Why do we need to import module1.module2
if we can just import module1
?
Example:
Why do we need import tkinter.messagebox
and do tkinter.messagebox.askyesno(“blah text”)
when we also can do import os
and still can do os.path.join(“/“, “blah”)
?
I use import os
in my code regularly, and I saw in someone else’s code the import tkinter.messagebox
.
Upvotes: 1
Views: 190
Reputation: 12092
This is one rationale. Generally when people do a
import os
more often than not, they use methods that belong to both os.path
and os
like os.path. abspath()
and os.getcwd()
. So importing os
makes more sense. If you are assured you are going to use just the methods in os.path
you might as well import os.path
and it is perfectly fine.
Similarly, if you are sure you are gonna be using just the methods in tkinter.messagebox
you do
import tkinter.messagebox
Upvotes: 1
Reputation: 251363
You can only use module1.module2
without an explicit import if module1
itself imports module2
. For instance, os
internally imports one of several other path-handling modules (depending on the OS) and calls it path
. This path
is then just a variable inside the os
module that lets you access the os.path
module.
Upvotes: 2