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 Yfrom 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?help('module_name') function provides useful information about a module.help("modules")__file__ attribute (discussed in next slides), which contain the path where the module is installed
import datetime
print( datetime.__file__)
# /usr/lib/python3.5/datetime.py
__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__ - examplesCreate 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__ - examplesCreate 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