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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Perkovic, Chapter 7 Functions revisited Python Namespaces
Introduction to PHP MIS 3501, Fall 2014 Jeremy Shafer
COMP234 Perl Printing Special Quotes File Handling.
1 Lecture-4 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process Dale/Weems/Headington.
CS61A Lecture 2 Functions and Applicative Model of Computation Tom Magrino and Jon Kotker UC Berkeley EECS June 19, 2012.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Functions Part I (Syntax). What is a function? A function is a set of statements which is split off into a separate entity that can be used like a “new.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
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,
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
C++ Basics Structure of a Program. C++ Source Code Plain text file Typical file extension .CPP Must compile the C++ source code without errors before.
Input, Output, and Processing
1 Programs Composed of Several Functions Syntax Templates Legal C++ Identifiers Assigning Values to Variables Declaring Named Constants String Concatenation.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
1 C++ Syntax and Semantics, and the Program Development Process.
Copyright © 2012 Pearson Education, Inc. Chapter 2: Introduction to C++
Functions, Procedures, and Abstraction Dr. José M. Reyes Álamo.
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Chapter 0 Getting Started. Objectives Understand the basic structure of a C++ program including: – Comments – Preprocessor instructions – Main function.
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
1 CS161 Introduction to Computer Science Topic #9.
Introduction to Computing Using Python Namespaces – Local and Global  The Purpose of Functions  Global versus Local Namespaces  The Program Stack 
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
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,
Chapter 9 Separate Compilation and Namespaces. Copyright © 2005 Pearson Addison-Wesley. All rights reserved. Slide 2 Overview Separate Compilation (9.1)
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 12 Separate Compilation and Namespaces.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Separate Compilation and Namespaces.
1. COMPUTERS AND PROGRAMS Rocky K. C. Chang September 6, 2015 (Adapted from John Zelle’s slides)
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
1 Types of Programming Language (1) Three types of programming languages 1.Machine languages Strings of numbers giving machine specific instructions Example:
Today… Style, Cont. – Naming Things! Methods and Functions Aside - Python Help System Punctuation Winter 2016CISC101 - Prof. McLeod1.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
2.1 The Part of a C++ Program. The Parts of a C++ Program // sample C++ program #include using namespace std; int main() { cout
Chapter 7 Modular Design
Python’s Modules Noah Black.
G. Pullaiah College of Engineering and Technology
Python Let’s get started!.
Variables, Expressions, and IO
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Fundamentals of Programming I Managing the Namespace
Separate Compilation and Namespaces
Topics Introduction to File Input and Output
Functions, Procedures, and Abstraction
Introduction to Programming
5. Functions Rocky K. C. Chang 30 October 2018
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Topics Introduction to File Input and Output
Functions, Procedures, and Abstraction
 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.
Python Modules.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

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 Richard Enbody The Practice of Computing Using Python 2nd Edition. Addison Wesley.)

Objectives Explain the specification of modules. Become familiar with the use of docstrings in Python. Explain the use of modules and namespaces in Python. Describe and use the different forms of module import in Python. Explain the local, global, and built-in namespaces and the scope resolution.

Where do the modules come from? The term “module” refers to the design and/or implementation of specific functionality to be incorporated into a program. Modular-II MODULE Hello; FROM STextIO IMPORT WriteString; BEGIN WriteString("Hello World!"); END Hello. A Python module is a file containing Python definitions and statements. By convention, modules are named using all lower case letters and optional underscore characters.

EXERCISE 12.1 Import a module. Use help(module_name) or dir(module_name) to find out the functions available in that module. Use print(module_name) to find out what the module does. Use print(function_name.__doc__) to print out what the function does.

Interface, client and docstring A module’s interface is a specification of what it provides and how it is to be used. Any program code making use of a given module is called a client of the module. A docstring is a string literal denoted by triple quotes used in Python for providing the specification of certain program elements.

EXERCISE 12.2 Try Import the graphics module dir(graphics) help(graphics) print(graphics.__doc__)

Documentation String (docstring) ( A docstring is a string literal denoted by triple quotes given as the first line of certain program elements. These additional lines must be indented at the same level. The docstring for a module is simply the first block of quoted text to appear in the module. Write docstrings for all public modules, functions, classes, and methods. Convention: """Return a foobang Optional plotz says to frobnicate the bizbaz first. """

EXERCISE 12.3 Write docstrings for your previous assignment.

EXERCISE 12.4 Run graphics.py as a main module. Run graphics.py as an imported module, for example, using your code for Q2 in A6. What is the difference between the two?

Running a module as main or imported module Before executing the code, the Python interpreter will define a few special variables, e.g., __name__. If the python interpreter is running that module (the source file) as the main program, it sets the special __name__ variable to have a value "__main__". If this file is being imported from another module, __name__ will be set to the module's name. test() in graphics.py will be executed only when the module is run as main: if __name__ == "__main__": test() See

EXERCISE 12.5 Create a simple module a (e.g., just printing out a message) and put it in your folder for modules (not in the Lib folder under Python-3.4.1) Create another simple module b that imports module a. Run module b.

Searching for imported modules Each imported module of a Python program needs to be located and loaded into memory. Python first searches for modules in the current directory. If the module is not found, it searches the directories specified in the PYTHONPATH environment variable. If the module is still not found, a Python installation- specific path is searched (e.g., C:\Python32\Lib ). If the program still does not find the module, an ImportError exception is reported.

The main and imported modules The main module may import any number of other modules (and each of those modules import other modules, etc.). Main modules are not meant to be imported into other modules. The statements of imported modules are executed only once, the first time that the module is imported. When a module is loaded, a compiled version of the module with file extension.pyc is automatically produced. Imported modules: Standard library (usually written in C) or Other modules (usually written in Python)

EXERCISE 12.6 Try the code on the next page. What will be printed out? Next, comment the two print statements inside the functions and run it again. Now, add x = 10 before x = funA() and run it again.

# A module def funA(): # x is a local variable x = 1 print(x) return x def funB(): # x is a local variable x = 2 print(x) return x # x is a global variable x = funA() x = funB() x = 0 print(x)

Global and local variables A local variable is a variable that is only accessible from within the function it resides. Such variables are said to have local scope. A global variable is a variable defined outside of any function definition. Such variables are said to have global scope. The use of global variables is considered bad programming practice.

Modules and Namespaces A namespace is a container that provides a named context for a set of identifiers (for variables, functions, and constants). A name clash is when two otherwise distinct entities with the same name become part of the same scope. In Python, each module has its own namespace. This includes the names of all items in the module, including functions and global variables—variables defined within the module and outside the scope of any of its functions. Therefore, the fully qualified name of a function (e.g., math.sqrt() ) in a (e.g., math ) module is used when the module is imported.

EXERCISE 12.7 Use the interactive mode for this exercise. 1. Restart the shell. 2. Type dir(). 3. Run the module in Exercise Type dir(). 5. Repeat steps 1-4 for graphics.py.

A module's/global namespace In Python, the main module of any program is the first (“top-level”) module executed. When working interactively in the Python shell, the Python interpreter functions as the main module, containing the global namespace. The namespace is reset every time the interpreter is started. Six names are always there: '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'

EXERCISE 12.8 In the shell used for the last exercise, import another module and then find out the updated namespace by dir(). Consider the following four cases: import math from math import sqrt, log from math import sqrt as new_sqrt from math import *

Importing modules When using import module_name, the namespace of the imported module becomes available to, but not part of, the importing module. The imported identifiers must be referenced fully qualified. When using from module_name import something, the imported module’s namespace becomes part of the importing module’s namespace. The imported identifiers are referenced without being fully qualified.

From-import Three possible from-imports: from module_name import func1, func2 from module_name import func1 as new_func1 from module_name import * For import *, All of the identifiers are imported, except for those that begin with two underscore characters, which are meant to be private in the module. In Python, all the variables in a module are “public,” with the convention that variables beginning with an two underscores are intended to be private.

EXERCISE 12.9 Try from math import * Define a new function: def ceil(x): if x - int(x) >= 0.5: return int(x)+1 else: return int(x) Execute ceil() to see which ceil() is used. Execute math.ceil().

Local, Global, and Built-in Namespaces During a Python program’s execution, there are as many as three namespaces: The built-in namespace contains the names of all the built-in functions, constants, and so on, in Python. The global namespace contains the identifiers of the currently executing module. The local namespace is the namespace of the currently executing function (if any).

EXERCISE Run the module in the next page. Try to understand what the outputs tell you.

import math globalX = 100 def getlocalnamespace(p1=123, p2="hihi"): localX = 10 print("\n=== local namespace ===") for key, val in locals().items(): print("key: {0:10} object: {1:10}".format(key, str(val))) def getglobalnamespace(): print("\n=== global namespace ===") for key, val in globals().items(): print("key: {0:20} object: {1:20}".format(key, str(val))) getlocalnamespace() getglobalnamespace()

locals() and globals() built-in functions locals() : Update and return a dictionary representing the current local symbol table. globals() : Return a dictionary representing the current global symbol table.

EXERCISE Run the module in the next page. Try to understand what the outputs tell you.

def getbuiltins(): builtin_dict = __builtins__.__dict__ print("\nBuiltin dictionary has {} entries\n".format(len(builtin_dict))) for key, val in builtin_dict.items(): print("key: {0:20} object: {1:20}".format(key, str(val))) getbuiltins()

The builtins module When the Python interpreter starts up, it loads two default modules without requiring an import: __main__ and __builtins__. This module provides the built-in functions and built-in constants. More details on this module:

EXERCISE Use the code on slide 15. Insert the codes for printing the local namespaces in funA() and funB(), and the global namespace.

Scope resolution Scope of a name (identifier) is the set of program statements over which it can be referred to. The scope of a name depends on where it is created and whether the name is used somewhere else. Local and global scopes When encountering a name, Python interpreter will search it in the order below: Local Enclosing (don't worry about it) Global Built-in

EXERCISE Run the code below and try to explain the result. x = 1 def fun(): x = x + 1 print(x, "x inside fun()") print(x, "x outside fun()") fun()

The local assignment rule If anywhere in a function an assignment is made, then that assignment is assumed to create a name only in the presently active namespace. If, within a function, a variable is declared to be a global variable using the global statement, then Python will not create a local name in the namespace for that variable.

END