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.

Slides:



Advertisements
Similar presentations
Lilian Blot CORE ELEMENTS PART V: FUNCTIONS PARAMETERS & VARIABLES SCOPE Lecture 5 Autumn 2014 TPOP 1.
Advertisements

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.
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
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.
This Week More Types boolean string Modules print statement Writing programs if statement Type boolean.
Perkovic, Chapter 7 Functions revisited Python Namespaces
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Introduction to Computing Using Python Namespaces and Exceptions, revisited  Encapsulation in Functions  Global versus Local Namespaces  Exceptional.
Programming for Engineers in Python
Tcl and Otcl Tutorial Part I Internet Computing KUT Youn-Hee Han.
Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –
Geography 465 Modules and Functions Writing Custom Functions.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
 2002 Prentice Hall. All rights reserved. 1 Chapter 4 – Control Structures Outline 4.1 Introduction 4.2 Program Components in Python 4.3 Functions 4.4Module.
 2002 Prentice Hall. All rights reserved. 1 Functions Purpose –Building blocks for the program (separate functionality in independant parts) –Avoid code.
FORTRAN.  Fortran or FORmula TRANslation was developed in the 1950's by IBM as an alternative to Assembly Language. First successfull high level language.
1 Python Chapter 2 © Samuel Marateck, After you install the compiler, an icon labeled IDLE (Python GUI) will appear on the screen. If you click.
Introduction to Computing Using Python Dictionary container class + modules  Container Class dict  Modules, revisited.
CSC 110 Numeric data types [Reading: chapter 3] CSC 110 D 1.
Fortran 1- Basics Chapters 1-2 in your Fortran book.
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
1 TAC2000/ Protocol Engineering and Application Research Laboratory (PEARL) MATH Functions in C Language.
Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
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.
H3D API Training  Part 3.1: Python – Quick overview.
Modules and Decomposition UW CSE 190p Summer 2012 download examples from the calendar.
Scons Writing Solid Code Overview What is scons? scons Basics Other cools scons stuff Resources.
Python From the book “Think Python”
Linux Operations and Administration
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.
Libraries Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
MA/CS 375 Fall 2002 Lecture 3. Example 2 A is a matrix with 3 rows and 2 columns.
© David Kirk/NVIDIA and Wen-mei W. Hwu, ECE498AL, University of Illinois, Urbana-Champaign 1 ECE498AL Lecture 4: CUDA Threads – Part 2.
More Python!. Lists, Variables with more than one value Variables can point to more than one value at a time. The simplest way to do this is with a List.
Parallel Programming Basics  Things we need to consider:  Control  Synchronization  Communication  Parallel programming languages offer different.
MA/CS 375 Fall 2003 Lecture 3. .* Multiplication We can use the.* operator to perform multiplication entry by entry of two matrices:
Introduction to MATLAB 1.Basic functions 2.Vectors, matrices, and arithmetic 3.Flow Constructs (Loops, If, etc) 4.Create M-files 5.Plotting.
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
MA/CS 375 Fall 2002 Lecture 2. Motivation for Suffering All This Math and Stuff Try the Actor demo from
Chapter 15. Modules Dr. Bernard Chen Ph.D. University of Central Arkansas Spring 2012.
Xi Wang Yang Zhang. 1. Easy to learn 2. Clean and readable codes 3. A lot of useful packages, especially for web scraping and text mining 4. Growing popularity.
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.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
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.
Python I/O Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Classic file reading 1 infile = open(’filename.txt’, ’r’) for line.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
Development Environment
Chapter 6 - Functions modular programming general function format
Python’s Modules Noah Black.
G. Pullaiah College of Engineering and Technology
Lecture 2 Python Basics.
Modules and Packages Damian Gordon.
Department of Computer Science,
Python’s Modules by E. Esin GOKGOZ.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
CSC/ECE 517 Introduction to Ruby.
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
Introduction to Value-Returning Functions: Generating Random Numbers
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
Terminal-Based Programs
Python Modules.
Review We've seen that a module is a file that can contain classes as well as its own variables. We've seen that you need to import it to access the code,
 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.
Presentation transcript:

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 and use. A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file consisting of Python code. A module can define functions, classes, and variables. A module can also include runnable code. Example: The Python code for a module named aname normally resides in a file named aname.py. Here's an example of a simple module, hello.py def print_func( par ): print "Hello : ", par return

The import Statement: You can use any Python source file as a module by executing an import statement in some other Python source file. import has the following syntax: import module1[, module2[,... moduleN] When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. Example: import hello hello.print_func("Zara") This would produce following result: Hello : Zara A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

It is also possible to import all names from a module into the current namespace by using the following import statement: from modname import * This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly. Locating Modules: When you import a module, the Python interpreter searches for the module in the following sequences: The current directory. If the module isn't found, Python then searches each directory in the shell variable PYTHONPATH. If all else fails, Python checks the default path. On UNIX, this default path is normally /usr/local/lib/python/. The module search path is stored in the system module sys as the sys.path variable. The sys.path variable contains the current directory, PYTHONPATH, and the installation-dependent default. The from...import * Statement:

The PYTHONPATH Variable: The PYTHONPATH is an environment variable, consisting of a list of directories. The syntax of PYTHONPATH is the same as that of the shell variable PATH. Here is a typical PYTHONPATH from a Windows system: set PYTHONPATH=c:\python20\lib; And here is a typical PYTHONPATH from a UNIX system: set PYTHONPATH=/usr/local/lib/python

Namespaces and Scoping: Variables are names (identifiers) that map to objects. A namespace is a dictionary of variable names (keys) and their corresponding objects (values). A Python statement can access variables in a local namespace and in the global namespace. If a local and a global variable have the same name, the local variable shadows the global variable. Each function has its own local namespace. Class methods follow the same scoping rule as ordinary functions. Python makes educated guesses on whether variables are local or global. It assumes that any variable assigned a value in a function is local. Therefore, in order to assign a value to a global variable within a function, you must first use the global statement. The statement global VarName tells Python that VarName is a global variable. Python stops searching the local namespace for the variable. For example, we define a variable Money in the global namespace. Within the function Money, we assign Money a value. therefor Python assumes Money is a local variable. However, we access the value of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the global statement fixes the problem.

Example: Money = 2000 def AddMoney(): Money = Money + 1 print Money AddMoney() print Money

The dir( ) Function: The dir() built-in function returns a sorted list of strings containing the names defined by a module. The list contains the names of all the modules, variables, and functions that are defined in a module. Example: import math content = dir(math) print content; This would produce following result: ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

The globals() and locals() Functions: The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. If locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function.

The reload() Function: When the module is imported into a script, the code in the top-level portion of a module is executed only once. Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. Syntax: The syntax of the reload() function is this: reload(module_name) Here module_name is the name of the module you want to reload and not the string containing the module name. For example to re-load hello module, do the following: reload(hello)

Packages in Python: Example: Consider a file Pots.py available in Phone directory. This file has following line of source code: def Pots(): print "I'm Pots Phone" Similar way we have another two files having different functions with the same name as above: Phone/Isdn.py file having function Isdn() Phone/G3.py file having function G3()

Now create one more file __init__.py in Phone directory : Phone/__init__.py To make all of your functions available when you've imported Phone, you need to put explicit import statements in __init__.py as follows: from Pots import Pots from Isdn import Isdn from G3 import G3 Note: Application file (e.g. package.py) should be saved in the parent directory of Phone sub-directory.