I have a main file, called ‘main.py’ and two subfolders. One is called ‘externals’ and contains ‘easygui.py’ and the other one is called ‘modules’ and contains a file called ‘gui.py’.
The program is started via main.py
I import easygui in main.py with import externals.easygui. The same way I import modules.gui
But when I call the welcome-function, It does not know easygui, I have to import it in the function. As I want to call more easygui-functions, I don’t want to import easygui in every def.
How can this be solved?
Thanks in advance!
Steffen
Examples (for readability without try/except and comment stuff):
main.py:
#!/usr/bin/env python
import externals.easygui
import modules.gui
main():
gui.welcome()
gui.py:
def welcome():
msgbox("Welcome!", ok_button="Ok")
Assuming that
welcomeis ineasygui.py, you want:As these things can get tedious to type, it’s often customary to import subpackages under an abbreviated name:
Alternatively, if you can make the whole thing a package by adding
__init__.py, and then you can control the namespace which gets imported from there …As far as sideways imports go, here’s a test directory structure I set up:
Now, (for simplicity) each
__init__.pysimply imports the files/modules contained in that directory. So, in steffen:and in external
and so forth.
for the actual code:
main.py:
easygui/gui.py:
external/welcome.py
Now I can use all of this. In the parent directory of steffen (just to make sure the package steffen is on PYTHONPATH), I can:
Phew! Now, it’s a little silly to have
steffen.main.main(). If you want to refer to the function as juststeffen.main(), you can set that up insteffen.__init__.py. Just change it to:So, if you would call a function by
foo.func()in__init__.py, you’ll call it assteffen.foo.func()in a script that importssteffen. Likewise, if you would call the function asfoo()in__init__.py, you’ll call it assteffen.foo()in a script that imports steffen. Hopefully that makes sense. There’s a lot to digest in this simplest working example I could come up with. The upside, if you can work through all of this and understand it, then you know almost everything there is to know about writing python packages (we haven’t talked about relative imports which could be used here too, or about writing asetup.pyto actually install your package, but those are fairly easy to understand once you understand this stuff).