Created for
Its just simple as creating a Python file - do not forget the .py extension
├── my_app
│ ├── app.py # the main file
│ ├── helper_module.py # a module file
import X
# import the helper_module:
import helper_module
# use helper_module
user_name = helper_module.get_user_name()
helper_module.greet(user_name)
import X as Y
import helper_module as hm
user_name = hm.get_user_name()
hm.greet(user_name)
from X import Y
from X import Y
notation. After that, you can use the name (Y), without having to prefixing it.
from helper_module import get_user_name, greet
user_name = get_user_name()
greet(user_name)
from X import *
from helper_module import *
user_name = get_user_name()
greet(user_name)
import
looks for a module?
$ tree my_app
my_app/
├── app.py
├── lib
│ ├── helper_module.py
import lib.helper_module as hm
user_name = hm.get_user_name()
hm.greet(user_name)
__init__.py
__init__.py
file in the directory, which you want it to be treated as package from Python.__init__.py
can be an empty file
$ tree my_app
my_app/
├── app.py
└── packA
├── greet.py
├── __init__.py
└── packB
├── get_data.py
└── __init__.py
__name__
.py
file, it executes the code in it!.py
file is executed as a module:__name__
is set to module's own filename.py
file is executed as stand-alone program:__name__
is set to "__main__"
__name__ - examples
Create in same directory next Python files:
import helper_module
if __name__ == "__main__":
print("helper_module is executed as stand-alone py file")
else:
print("helper_module is imported as module")
main.py
and look at the outputhelper_module.py
and look at the output__file__
__file__ - examples
Create in same directory next Python files:
import helper_module
print( "__file__:", __file__)
main.py
and look at the outputhelper_module.py
and look at the outputThese slides are based on
customised version of
framework