I’m a little confused by the from import statements in Python. In particular, how I can import a class from a module that is within a package. For example, if I have a package named my package that has two modules (module 1 and module 2), how can I import a specific class from module 1 within module 2?
What I’m finding currently is that I need to (within module two) do the following…
from package import module1
module1.class1()
While this works, I’d much rather be able to access class1() directly from module 2 as it is not very readable . However, the following syntax doesn’t work…
from package import module1.class1
Also, it won’t let me simply go…
from module1 import class1
How does one import a class which is in a module within a package, directly within a separate module within that package?
You were on the right track:
If as you say you’re importing from within the same package, you can also do
The
.means “the position in the package hierarchy of the module doing the importing”. See the documentation for info.