How to import class from a Python package directly
Question:
My current package looks something like this:
package_repo/
package/
__init__.py
module_one.py
module_two.py
tests/
setup.py
Inside the module_one.py
I have ClassOne
,and inside the module_two.py
I have ClassTwo
. Now, if I want to import ClassOne
into some other module, I write from package.module_one import ClassOne
.
Is it possible to import ClassOne
directly from package
as in from package import ClassOne
or import package as pkg
and then use classes as pkg.ClassOne()
? If yes, how to do it? I am asking because that is just more elegant.
Answers:
Inside the __init__.py file in your package, you can declare and initialize anything you want, including imports!
So, write inside it this:
from module_one import ClassOne
from module_two import ClassTwo
Doing so, now those classes will be known and can be imported directly from the package, as:
from package import ClassOne, ClassTwo
And yes, you can also do it like:
import package as pkg
pkg.ClassOne()
My current package looks something like this:
package_repo/
package/
__init__.py
module_one.py
module_two.py
tests/
setup.py
Inside the module_one.py
I have ClassOne
,and inside the module_two.py
I have ClassTwo
. Now, if I want to import ClassOne
into some other module, I write from package.module_one import ClassOne
.
Is it possible to import ClassOne
directly from package
as in from package import ClassOne
or import package as pkg
and then use classes as pkg.ClassOne()
? If yes, how to do it? I am asking because that is just more elegant.
Inside the __init__.py file in your package, you can declare and initialize anything you want, including imports!
So, write inside it this:
from module_one import ClassOne
from module_two import ClassTwo
Doing so, now those classes will be known and can be imported directly from the package, as:
from package import ClassOne, ClassTwo
And yes, you can also do it like:
import package as pkg
pkg.ClassOne()