Python ModulesModules in a NutshellModule ExampleUsing a moduleCall by ValueAccessing the module variablesfrom/import StatementsThe Importance of ReturningModules as Scripts.pyc Filesdir()Standard ModulesA Package ExampleImporting PackagesSlide 15SourcePYTHON MODULESModules in a NutshellModules are text files you can import to the Python interpreter in order to reuse previously written code.A module has its own global and local scopes to prevent interference with user defined names.A package is a collection of modules, grouped for organization and easy access.Module Example$ vim mymodule.py#a simple moduledef square(x):“””Returns the square of its parameter.“””return x * xUsing a module>>> import mymodule>>> y = mymodule.square(2)>>>y4>>>mymodule.square(y)16Call by Value>>> import mymodule>>> x = 7>>> mymodule.square(x)49>>> x7Accessing the module variablesYou can access the global variables of a module using dot notation.>>> x = somemodule.somevariableGlobal variables in a module will not otherwise effect another module, or user defined components.from/import StatementsYou can import specific names from a module with a from/import statement.>>> from mymodule import square>>> square(3)9>>> from mymodule import square, cube>>> cube(2)8>>> from mymodule import *The Importance of ReturningPython modules don’t really handle function calls by reference. Programmers have to work around this with return statements.>>> x = 2>>> x = mymodule.square(2)>>> x4Modules as Scripts$ vim mymodule.pydef square(x):print x * xif __name__ == "__main__": import sys square(int(sys.argv[1]))~~$ python mymodule.py 24.pyc FilesOn a successful import, a modulename.pyc file is generated. This file contains the bytecode from the last time the modulename.py file was imported.The interpreter checks the date modified before using the .pyc file, there is no danger of using an older version.These files only speed up the loading of a module, not the execution.dir()dir() is useful for checking what modules you’ve imported.>>> dir()['__builtins__', '__doc__', '__name__', '__package__']>>> import mymodule>>> from mymodule import square>>> dir()['__builtins__', '__doc__', '__name__', '__package__', 'mymodule', 'square']Standard Modulesimport first checks the current directory for the specified module.The interpreter then follows a default path like /usr/local/lib/python, or the PYTHONPATH EV.To change the path, import “sys”, one of Python’s standard modules.>>> import sys>>> sys.path.append(‘/home/jm4564/cs_265’)A Package Examplemath/__init__.pylogarithms.pycircles.pystatistics/factorial.py……Importing PackagesPackages can be imported in as large, or as small, portions as you require.>>> import math.circles>>> math.circles.area(5)78.53981634>>> from math.circles import area>>> area(3)28.27433388Questions?SourcePython v2.6.4 documentation >> The Python Tutorial >>
View Full Document