MODULE AND PACKAGE
Dr. Kyi Pyar @ Chit Su
CREATE MODULE
• Create a python code file and then give the file a name with a “ .py” extension.
Several objects are defined
in mod.py:
•s (a string)
•a (a list)
•foo() (a function)
•Foo (a class)
USE MODULE OR IMPORT MODULE
• Syntax : import <module_name>
Import mod for reusing several
objects
•s (a string)
•a (a list)
•foo() (a function)
•Foo (a class)
VIEW MODULE LOCATION
• Once a module has been imported, the location can view with the module’s __file__
attribute:
IMPORT WHOLE MODULE
• import <module_name> (or) from <module_name> import *
• The simplest form is the one already shown above:
Import mod for reusing all objects and
functions
•s (a string)
•a (a list)
•foo() (a function)
•Foo (a class)
IMPORT ONLY REQUIRE OBJS OR FUNS
• from <module_name> import <name(s)>
• An alternate form of the import statement allows individual objects from the module
Import mod for reusing only:
•s (a string)
•foo() (a function)
THE DIR() FUNCTION
• The built-in function dir() returns a list of defined names in a namespace.
PYTHON PACKAGES
CREATE PACKAGE
• Creating a package is quite straightforward, since it makes use of the operating system’s
inherent hierarchical file structure.
• Library or package is the folder in which related modules are included.
EXAMPLE CREATION OF PACKAGE
• Here, there is a directory named pkg that contains two modules, mod1.py and mod2.py. The
contents of the modules are:
IMPORT MODULE FORM
PACKAGE
• Given this structure, if the pkg directory resides in a location where it can be found (in one
of the directories contained in sys.path), you can refer to the two modules with dot notation
(pkg.mod1, pkg.mod2) and import them with the syntax you are already familiar with:
IMPORT ALL MODULE FORM THE PACKAGE