Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Modules.

Similar presentations


Presentation on theme: "Python Modules."— Presentation transcript:

1 Python Modules

2 Modules in a Nutshell Modules 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.

3 Module Example $ vim mymodule.py # a simple module def square(x): “”” Returns the square of its parameter. return x * x

4 Using a module >>> import mymodule >>> y = mymodule.square(2) >>>y 4 >>>mymodule.square(y) 16

5 Call by Value >>> import mymodule >>> x = 7 >>> mymodule.square(x) 49 >>> x 7

6 Accessing the module variables
You can access the global variables of a module using dot notation. >>> x = somemodule.somevariable Global variables in a module will not otherwise effect another module, or user defined components.

7 from/import Statements
You 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 *

8 The Importance of Returning
Python modules don’t really handle function calls by reference. Programmers have to work around this with return statements. >>> x = 2 >>> x = mymodule.square(2) >>> x 4

9 Modules as Scripts $ vim mymodule.py def square(x): print x * x if __name__ == "__main__": import sys square(int(sys.argv[1])) ~ $ python mymodule.py 2 4

10 .pyc Files On 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.

11 dir() dir() is useful for checking what modules you’ve imported.
['__builtins__', '__doc__', '__name__', '__package__'] >>> import mymodule >>> from mymodule import square ['__builtins__', '__doc__', '__name__', '__package__', 'mymodule', 'square']

12 Standard Modules import 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’)

13 A Package Example math/ __init__.py logarithms.py circles.py statistics/ factorial.py …

14 Importing Packages Packages can be imported in as large, or as small, portions as you require. >>> import math.circles >>> math.circles.area(5) >>> from math.circles import area >>> area(3)

15 Questions?

16 Source Python v2.6.4 documentation >> The Python Tutorial >> Modules


Download ppt "Python Modules."

Similar presentations


Ads by Google