Upload
david-watson
View
230
Download
2
Tags:
Embed Size (px)
Citation preview
Overview
Intro to functionsWhat are functions?Why use functions?Defining functionsCalling functionsDocumenting functionsTop-down designVariable scope and functionsParameters and argumentsGlobal variables and constants
Intro to ModulesWhat are modules?Why use modules?Importing and reloadingScope re-visited (Namespaces)Useful modulessys module and sys.argvModule name and __main__
What is a Function?
A function is a named sequence of statements that exists within a program to perform a specific taskSome are built-in to Python – dir(), help(), str(), int(), float(), input(), raw_input(), etc.Some are provided in other modules (e.g. math)Others you will code yourself …
Why use functions?
DRY – Don’t Repeat Yourself
Breaks long sequence of statements into function calls with names that convey what the group of statements do
Code is easier (faster) to: ReadReuseTest
Facilitates teamwork
vs.
Defining functions
Function definitions are composed of a function header (first line – including “:” !) and indented function block (body) with one or more statements
Function names cannot Be a Python keywordContain spacesBegin with a number or special character (except _ )Be called before they are defined
Function names arecamelCase in Python (PascalCase in C#)Verb clauses describing task
(e.g. getPopulationData)CaSE SenSItIve
Syntax:def functionName([params]): # Function Header pass # Function [return someObject] # body
Calling functions
Functions are called by name followed by parentheses (That may or may not contain arguments depending on whether or not the function definition contains parameters – more later)
Parameters and arguments
A parameter is a variable that receives an argument passed to a function.A parameter is local variable to the function definition An argument is data passed to a function when it is called.
messageText = parameter
“I love spam” = argument
Multiple parameters and arguments
Variable scope and functions
Variable scope = the parts of a program that can access (“see”) the variable.Local = accessible inside a function = can reuse variable names in different functions
Global variables and constants
Global = accessible to all functions in a program fileLimit the use of global variables !!!! They make debugging difficult and life miserableUse global constants where possible (UPPERCASE names).
Function with return
Return as short-circuit for function
If return statement is executed in a function, the interpreterreturns to statement that made the function call. No otherlines in the function are executed.
Use clear function and variable names
Most function names should be verb phrases not noun phrases.
Variable names should convey what their value is.
Boolean functions (return bool)should ask a yes/no question.
Documenting a FunctionSingle-line string (single or double quoted) or multi-line string (triple quoted) immediately following the function definition statement.
Top-down design
Break overall task into sub-tasksBreak sub-tasks into sub-tasks if possibleWhen complete, write “leaf” functions and work back to trunk (testing as you go)
Call list
Incremental development
Start with a simple test and function skeleton.
Run test repeatedly as you debug function under test.
Overview
Intro to functionsWhat are functions?Why use functions?Defining functionsCalling functionsDocumenting functionsTop-down designVariable scope and functionsParameters and argumentsGlobal variables and constants
Intro to ModulesWhat are modules?Why use modules?Importing and reloadingScope re-visited (Namespaces)Useful modulessys module and sys.argvModule name and __main__
What are Modules?
Modules are most typically .py or pyc files but can be DLL, etcMany modules and packages (groups of modules) shipped with Python (e.g. sys, os, math, turtle, etc.) Local modules (in same folder as running .py) override other modules in folders.
Example: arcgisscripting.py in local folder will override C:\Program Files\ArcGIS\bin\arcgisscripting.dll this is NOT a good thing.
Why use Modules?
Code reuseSaves code permanently to diskCan be referenced (imported) by multiple client modulesDefine data and methods that can be used in programs
Namespace partitioningSeals up names to avoid name clashes … e.g. two modules can have functions with the same name
- If you run a module as a program, the built-in __name__ attribute contains __main__. - If you import, __name__ contains the name of the module (no .py extension).- Convention is to put this block at the end of the module.
How: Module contents and structure
Most modules have one or more of the attributes shown below
import <module> / from <module> import …
Import is only run once / module / Python session
If you edit the module file with external editor and save, and you are in the same Python session, then the updated file WILL NOT BE IMPORTED!Using from <module> import <name(s)> means you do not have to qualify the names with the module name
del () removes names
from program
B.py run twice …
reload(module)
The reload() function forces a module to reload – run its code.In an active session, Python is not aware of updates in imported modulesReally useful during program developmentShould not be used with stable modules
import steps
Find the module’s fileSearch folders in following order:
Folder containing the programPYTHONPATH directories (if it is set)Standard library directories
Compile it to byte code (maybe)If .py newer than .pyc and if file is imported
Run the module’s code to build the objects it defines
}
Structuring a Python program
a.py
b.py c.py
Std Library modules
Top-level module that controlsprogram flow. Imports b.
b and c import each other …not usually a good thing
and may import 0 or moreof the standard library modulesand 0 or more “other” modules
Other modules
Namespaces
Scope rules
Python searches for names in LEGB order and stops at the first name it finds (i.e. Local x takes precedence over EGB
Local: in a function and not declared global (e.g. global x)Enclosing functions: nested functions
Not covered in this course
Global (module): names at top-level of moduleBuilt-in: names in Python built-in names module (e.g. open, range, etc.)
Built-in & Standard Python library modules
Built-in functions can be called without importing any module
Standard Python Library modules must be imported to gain access to functions, etc.
Some useful Python Modules
globmathosos.pathshutilsyszipfile
sys module & command line args (sys.argv)
Command line args are stored in sys.argv
sys.exit([arg])
The exit function in stops execution of a Python program
os and os.path module
Access to operating system properties / operations
Get/Set environment variables, get current directory, creating/deleting directories, path/file info, split/join paths Three ways to specify paths
in Python:
os.path module (splitting/joining paths)
glob - Filename globbing utility
The glob module finds all the pathnames matching a specified pattern
shutil – file/dir tree copy/move/delete(rm)
The shutil module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal.
Implementation of shutil.copytree
Other modules
zipfile module – working with .zip files (read, write, get info, etc.)
The urllib2 module defines functions and classes which help in opening URLs (mostly HTTP)
main()
Most programs contain a function called main that has the a program’s mainline logicThat is, standalone statements and calls to other functions in a logical order.
__main__ and main()
In many Python scripts you will find the following at the bottom of modules
In plain English … If the module is running as a program (i.e. not imported), then __name__ will be __main__ so call the main() function defined in the module.If the module was imported, __name__ will be the name of the module and main() will not be called.
Lib, Modules, function mind map