Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 15-18 Modules CSC1310 Fall 2009. Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.

Similar presentations


Presentation on theme: "Chapter 15-18 Modules CSC1310 Fall 2009. Modules Modules Modules are the highest level program organization unit, usually correspond to source files and."— Presentation transcript:

1 Chapter Modules CSC1310 Fall 2009

2 Modules Modules Modules are the highest level program organization unit, usually correspond to source files and serve as libraries of tools. Each file is a module and modules import other modules to use the name they define. import import: lets a client fetch a module as a whole from from: allows to fetch particular names from module reload reload: provides a way to reload code without stopping Python.

3 Why Use Modules? Code reuse 1. Code reuse Code in module is persistent: can be reloaded and run as many times as needed. System namespace partitioning 2. System namespace partitioning Everything “lives” in a module: code and objects are always implicitly enclosed by a module. Implementing shared services or data 3. Implementing shared services or data Components shared across a system

4 Module Creation Easy to create Easy to create: files that are created with text editor. attributes Top-level assignments create module attributes..py You can call modules anything (except keywords), but module filenames should end in.py extension

5 Modules Usage: import import Clients can use the module file by running import statement >>>import math # file to be loaded >>>print math.pi # variable in the script >>>print math.sqrt(4), math.log(10) importwhole module object import gives the whole module object is necessary Module name is necessary to fetch (use, call) its attributes

6 Modules Usage: from from Clients can use the module file by running from statement >>>from math import pi, sqrt >>>print pi,sqrt(6) fromspecified names from copies specified names out of the module. withoutmodule The copied names are used directly without going through module.

7 Modules Usage: from * from* Special form of from statement (with *) gives copies of all names in the referenced module. >>>from fib import * >>>print fibTopN(6), fib(6), list, add() without module The copied names are used directly without going through module.

8 Import Runs Only Once importfrom Import is expensive operation, so it happens only on first import of from. code is not rerun Later import operations fetch an already- loaded module object (code is not rerun!)

9 import, from are Assignments import import assigns an entire module object to a single name. from from assigns one or more names to objects of the same name in another module. from Name copied with from becomes a reference to a shared object (fetched mutable object can be changed). >>>from fib import list, size >>>list[0]=“changed!”, size=12 Cross-File Name Changes Cross-File Name Changes: >>>import fib >>>fib.size=23 #earlier “size” was 12 which is still 12

10 Rename import, from Both import, from were extended to allow a module to be given a different name. as >>>import fib as f >>>print f.multiple() as >>>from fib import multiple as mult >>>print mult([1,2,3]) Short synonyms for long names. Avoiding name clashes.

11 Reloading Modules reload reload function forces already loaded module code to be reloaded and rerun. Assignments in the new code change the existing module object in-place. It allows to change parts of running programs without stopping. reload reload is passed an existing module object, not a name. >>>import fib …. >>>reload(fib)

12 reload Basics reload reload runs a module file’s new code in the module’s current namespace. all import Impacts all files that use import. futurefrom from Impacts only future from clients only, since previous from clients got a copy not a reference to an object.

13 reload Example In interactive shell In interactive shell: >>>import fib >>>print fib.multiple() Change fib.py Change fib.py: list2=[‘a’,’b’,’c’,’d’,’e’] def multiple(l=list2): return [l[x]*x for x in range(len(l))] In interactive shell In interactive shell: >>>reload(fib) >>>print fib.multiple()

14 reload Example In interactive shell (before changes) In interactive shell (before changes): >>>from math import sqrt,pi >>>print pi You change pi You change pi >>>pi = 3.0 >>>pi = 3.0 In interactive shell you try: In interactive shell you try: from >>>reload(math) # doesn’t work, from assigned pi and sqrtmath name pi and sqrt, not name math >>>import(math) >>>reload(math) >>>print pi # from makes copy of function! So, you need either: So, you need either:  Call it math.pi OR Rerun the from (from math import pi)

15 Data Hiding in Modules convention Data hiding in Python is a convention, not a syntax. You can not prevent changes from outside. _name from * Single leading underscore in name (_name) prevents variable from being copied with from *. __all__ __all__from * Hiding effect can be achieved by assigning a list of variable name string to the global variable __all__. If __all__ is defined, from * copies only variable mentioned there; otherwise, it copies all variables without a single leading underscore. _x=3 __all__=["add","fib","list"]

16 Mixed Usage Modes __name__: Each module has a built-in attribute __name__:  “__main__”  “__main__” if file is being run as a top-level program  module’s name  module’s name if file is being imported Module can test its own __name__ to determine whether it’s being run or imported(different behavior, testing) In runme.py import fib def imported(): print “It is imported” if __name__==“__main__”: print fib.fib(4)

17 Changing the Module Search Path sys.path Program can change the search path by changing a built-in list called sys.path sys.path is initialized on startup, but then you can delete, append, and reset its components: >>>import sys \\ >>>sys.path.append(“c:\\Temp”) Be careful Be careful: if you delete a critical directory from the path, you may lose access to critical utilities. Your settings are not retained after Python exits.

18 Module Design Concepts always in a module __main__ You’re always in a module in Python. Indeed, code typed in interactive prompt really goes to built-in module __main__ Minimizecoupling Minimize module coupling: global variables. Maximizecohesion Maximize module cohesion: unified purpose. function return values Modules should rarely change other modules’ variables (function return values)

19 Importing Modules Dynamically >>>import ”string” >>>x=“string” >>>import x importstring exec If you get name to import dynamically, you need to construct an import statement as a string of Python code and pass it to exec. >>>name=“string” >>>exec “import”+name exec exec statement compiles a string of code and passes it to Python interpreter to be executed. __import__ exec __import__ loads from a string and returns the module object. It works quicker than exec. >>>string=__import__(name)


Download ppt "Chapter 15-18 Modules CSC1310 Fall 2009. Modules Modules Modules are the highest level program organization unit, usually correspond to source files and."

Similar presentations


Ads by Google