'Is there a way to shorten the input command for specific classes in my package?
I would like to create a package that has roughly this structure:
package
contrib
case1
src
__init__.py
case1.py
class case1
+ other functions
data
case2
src
__init__.py
case2.py
class case2
+ other functions
data
case3
...
The user will get access to caseX by accessing class caseX in the caseX subfolder.
I went with this format to make it simple for others to contribute their own cases. The idea is that a contributors can, one day, add their own cases by creating a new caseY subfolder in the contrib folder.
However, this structure makes the import command for the classes very long. It would be something like this:
from package.contrib.case1.src.case1 import case1
My question is: Is there a way to shorten the import command? Ideally, I would want to import the class caseX' from the classX` subfolder by simply writing this:
from package import case1
Is that possible?
Solution 1:[1]
If anyone is also having these issues, I figured it out using the importlib package. In the directory /package/contrib/ I added the following to __init__.py:
import importlib
# Add one of these for each class I want to directly load using import
case1 = getattr(importlib.import_module("case1.src.case1", package='package'), "case1")
case1.src.case1 is the path to the file case1.py in Python "dot" notation. The last bit (... , "case1")) refers to the class case1 in the file case1.py.
Now I can write this command and get direct access to the class:
from package import case1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | partypeter |
