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

Slides:



Advertisements
Similar presentations
Lilian Blot PART V: FUNCTIONS Core elements Autumn 2013 TPOP 1.
Advertisements

Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
15. Python - Modules A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand.
Python Mini-Course University of Oklahoma Department of Psychology Day 1 – Lesson 4 Beginning Functions 4/5/09 Python Mini-Course: Day 1 - Lesson 4 1.
Setting the PYTHONPATH PYTHONPATH is where Python looks for modules it is told to import List of paths Add new path to the end with: setenv PYTHONPATH.
Perkovic, Chapter 7 Functions revisited Python Namespaces
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
An Introduction to Python – Part IV Dr. Nancy Warter-Perez June 23, 2005.
Geography 465 Modules and Functions Writing Custom Functions.
Tutorial 6 & 7 Symbol Table
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
CS 201 Functions Debzani Deb.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
PYTHON: LESSON 1 Catherine and Annie. WHAT IS PYTHON ANYWAY?  Python is a programming language.  But what’s a programming language?  It’s a language.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
Python Programming Fundamentals
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
INTRODUCTION TO PROGRAMMING STRUCTURE Chapter 4 1.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Modules and Decomposition UW CSE 190p Summer 2012 download examples from the calendar.
Linux Operations and Administration
Oct 15, 2007Sprenkle - CS1111 Objectives Creating your own functions.
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Chapter Function Basics CSC1310 Fall Function function (subroutine, procedure)a set of statements different inputs (parameters) outputs In.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
You Need an Interpreter!. Closing the GAP Thus far, we’ve been struggling to speak to computers in “their” language, maybe its time we spoke to them in.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
Python Let’s get started!.
Function Basics. Function In this chapter, we will move on to explore a set of additional statements that create functions of our own function (subroutine,
Agenda The Bourne Shell – Part II Special Characters Ambiguous File Reference Variable Names and Values User Created Variables Read-only Variables (Positional.
Chapter 15. Modules Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Creating FunctionstMyn1 Creating Functions Function can be divided into two groups: –Internal (built in) functions –User-defined functions.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Modules. Modules Modules are the highest level program organization unit, usually correspond to source files and serve as libraries of tools. Each file.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Today… Strings: –String Methods Demo. Raising Exceptions. os Module Winter 2016CISC101 - Prof. McLeod1.
Today… Modularity, or Writing Functions. Winter 2016CISC101 - Prof. McLeod1.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
CS 115 Lecture 5 Math library; building a project Taken from notes by Dr. Neil Moore.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Fundamentals of Programming I Overview of Programming
Topic: Python’s building blocks -> Variables, Values, and Types
Python’s Modules Noah Black.
G. Pullaiah College of Engineering and Technology
Lecture 2 Python Basics.
Modules and Packages Damian Gordon.
Topics Introduction to Repetition Structures
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Python Classes By Craig Pennell.
INFS 6225 – Object-Oriented Systems Analysis & Design
Topics Introduction to File Input and Output
Introduction to Python
Winter 2018 CISC101 12/5/2018 CISC101 Reminders
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Introduction to Value-Returning Functions: Generating Random Numbers
Terminal-Based Programs
Python Modules.
Topics Introduction to File Input and Output
 A function is a named sequence of statement(s) that performs a computation. It contains  line of code(s) that are executed sequentially from top.
SPL – PS1 Introduction to C++.
Python Modules.
Learning Python 5th Edition
Presentation transcript:

Chapter Modules CSC1310 Fall 2009

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.

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

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

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

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.

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.

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!)

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

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.

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)

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.

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()

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)

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"]

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)

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.

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)

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)