You are on page 1of 63

1

CHAPTER 2:
FUNCTIONS, MODULES AND
PACKAGES
2

CHAPTER OUTCOMES
• By the end of this chapter, the students will:
• Know how to write and create functions, modules as well as packages to solve
complex problems
• Know how to define and call a function (passing the correct corresponding
arguments)
• Be able to apply and use Python built-in functions and modules
3

PART 1 – FUNCTIONS
4

FUNCTIONS IN PYTHON
• The functions in Python are:
• Built-in functions: these functions pre-defined and are always
available.
• User defined functions: these are defined by the programmer.
• Functions defined in modules: these functions are pre-defined in
particular modules and can only be used when the corresponding
module is imported.
5

BUILT-IN FUNCTIONS
• The Python interpreter has a number of functions built into it that are
always available:
print():Prints to the standard output device
abs(x): Returns the absolute value of a number
float(): Returns a floating point number
int(): Returns an integer number
str(): Returns a string object
input():Allowing user input
len(): Returns the length of an object
list(): Returns a list
pow(x,y): Returns the value of x to the power of y
tuple(): Returns a tuple
sum(): Sums the items of an iterator
dir(str):Lists all the string function names
dir(list):Lists all the list function names
dir(dict):Lists all the dictionary function names
dir(tuple):Lists all the tuple function names

6

BUILT-IN FUNCTIONS: STRINGS


• Python has a set of built-in methods that you can use on string:
lower():converts a string into lower case
S=" Hello, World! " # the output:
print(S.lower()) hello, world!

isprintable(): Returns True if all characters in the string are printable


S=" Hello, World! “ # the output:
T=" Hello,\n World!“ True
print(S.isprintable()) False
print(T.isprintable())
isspace(): Returns True if all characters in the string are whitespaces
S="Hello, World!" # the output:
print(S.isspace()) False

istitle(): Returns True if the string follow the rules of a title


S="Hello, World!" # the output:
Print(S.istitle()) True
7

BUILT-IN FUNCTIONS: STRINGS


strip(): Removes any whitespace from the beginning or the end
S=" Hello, World! " # the output:
print(S.strip()) Hello, World!

replace(oldValue,NewValue):replaces a string with another string


S="Hello, World!" # the output:
print(S.replace("H","J")) Jello, World!

split(): splits the string into substrings if it finds instances of the


separator and returns a list
S="Hello, World!" # the output:
print(S.split()) ['Hello,' ' World!']
find(value): finds the first occurrence of the specified value and returns
-1 if the value is not found.
S="Hello, Hello!" # the output:
print(S.find("Hello")) 0

find(value,[start],[end]):the value to search for, Start[optional] where to


start the search (default is 0), end [optional] where to end the search
(default is to the end of the string).
8

BUILT-IN FUNCTIONS: STRINGS


index(value): finds the first occurrence of the specified value and raises
an exception if the value is not found
S=" Hello, Hello! " # the output:
print(S.index(“Hello”)) 1
rfind(): finds the last occurrence of a specified value otherwise returns-1
rindex(): finds the last occurrence otherwise raises an exception
S="Hello, Hello!" # the output:
print(S.rfind("Hello")) 7

join(string): takes all items in an iterable and joins them into one string, a
string must be specified as separator
S=("Hello","Hi“,"World! “) # the output:
print(“@".join (S)) Hello@Hi@World
9

BUILT-IN FUNCTIONS: LISTS


• Python has a set of built-in methods that you can use on list:
append(element): appends an element to the end of the list.
fruits = ['apple','banana'] # the output:
fruits.append("orange") ['apple', 'banana', 'orange']
print(fruits)

clear(): removes all the elements from a list


fruits = ['apple','banana'] # the output:
Fruits.clear() []
print(fruits)
insert(pos,element): inserts the specified value at the specified position
fruits = ['apple','banana'] # the output:
fruits.insert(1, “orange“) ['apple','orange‘,'banana']
print(fruits)
extend(list): adds a specified list of elements to the end of the current
list.

fruits = ['apple','banana'] # the output:


F=[‘cherry’,’orange’] ['apple','banana',‘cherry‘,'orange']
fruits.extend(F)
print(fruits)
10

BUILT-IN FUNCTIONS: DICTIONARY


• Python has a set of built-in methods that you can use on dictionary:
fromkeys(keys,val): returns a dictionary with the specified keys and values

D = (‘Key1',‘Key2‘) # the output:


X=0 {'key1': 0, 'key2': 0}
print(dict.fromkeys(D,x))
pop(): removes the specified item from the dictionary

student = { # the output:


“name":“Med", IT
“Major":“IT", {'name': 'Med', 'year': 2019}
"year":2019
}
print(student.pop(“Major“))
print(student)

values(): returns a view object


print(student.values()) # the output:
dict_values(['Med', 'IT', 2019])
11

BUILT-IN FUNCTIONS: TUPLE


• Python has only two built-in functions that you can use on tuples:

count(value): returns the number of times a specified value appears in the


tuple
T=(1,3,7,8,7,5,4,6,5) # the output:
print(T.count(7)) 2

index(value): finds the first occurrence of the specified value and raises
an exception if the value is not found
T=(1,3,7,8,7,5,4,6,5) # the output:
print(T.index(7)) 2
12

USER DEFINED FUNCTIONS


• Function blocks begin with the keyword def followed by the function
name and parentheses ().
• Any input parameters or arguments should be placed within these
parentheses (Parameters are inside functions, while arguments are used
in function calls, i.e. the values passed to the function at run-time).
• The code block within every function starts with a colon (:) and is
indented.
• The statement return [expression] exits a function, optionally passing back
an expression to the caller. A return statement with no arguments is the
same as return None.
def functionname( parameters):
function_suite
return [expression]
13

CREATING A FUNCTION
• Examples
def my_function():
print("Hello from a function")

def sum(a,b):
return (a+b)

def small(a,b):
if (a<b):
d=a
else:
d=0
return d
14

CREATING A FUNCTION
• Examples
def Min(a,b):
if (a<b):
return a
else:
return b

def Min(a,b):
if (a<b):
return a
elif (a>b):
return b
else:
s=‘there are equal’
return s
15

CALLING A FUNCTION
• To call a function, use the function name followed by parenthesis and
arguments.
• Function Arguments: You can call a function by using the following
types of formal arguments

• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
16

CALLING A FUNCTION
• Required arguments: are the arguments passed to a function in
correct positional order. Here, the number of arguments in the
function call should match exactly with the function definition.
x=2
y=4
print(sum(x,y))
# the output:
6

print(small(2,4))

# the output:
2

x=2
y=4
print(small(x,y))
# or print(small(a=x,b=y))
17

CALLING A FUNCTION
• Keyword arguments: When you use keyword arguments in a function
call, the caller identifies the arguments by the parameter name. This
allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the
values with parameters.
def small(a,b):
if (a<b):
d=a
else:
d=0
return d
print(small(b=2,a=4))

# the output:
0
18

CALLING A FUNCTION
Exercise:
What are the ouputs of the following codes

def Info(name,age):
print ("Name: ",name)
print ("Age ",age)
return
#Now you can call Info function
Info( age=20, name=“Jim" )
Info(‘Marry’,30)
Info(50,40)
19

CALLING A FUNCTION
• Default argument: is an argument that assumes a default value if a
value is not provided in the function call for that argument. The
following example gives an idea on default arguments, it prints default
age if it is not passed.
• All arguments without default values must be listed before arguments
with default values in the function definition.
def Info(name,age=35):
print ("Name: ",name)
print ("Age ",age)
#Now you can call Info function
Info( age=20, name=“Jim" )
Info(‘Mack’)

# the output:
Name: Jim
Age 20
Name: Mack
Age 35
20

CALLING A FUNCTION
Exercise:
What are the ouputs of the following codes

def Greet(name,msg=‘Greetings!’): def Greet(msg=‘Greetings!’,name):


print (name +’, ’+msg) print (msg +’, ’+name)
return return
#Now you can call Greet function #Now you can call Greet function
Greet(“Jack","Good morning!") Greet("Good morning!“,“Jack")
Greet(“Yvonne","Good afternoon!") Greet("Good afternoon!“,“Yvonne")
Greet(“Jim","Good evening!") Greet(“Good evening!“,“Jim”)
Greet(“Marry") Greet(“Marry")
21

CALLING A FUNCTION
Variable-length arguments:
 In addition to named arguments, functions can accept two special
collections of arguments. In Python, we can pass a variable number of
arguments to a function using special symbols. There are two special
symbols:
 *args (Non Keyword Arguments)
 **kwargs (Keyword Arguments)
 The first is a named tuple. This special argument is identified by prefixing it
with a single asterisk (*).
 The second is a variable-length dictionary containing all keyword arguments
passed to the function that were not explicitly defined as part of the function
arguments. This argument is identified by prefixing it with two asterisks (**).
22

CALLING A FUNCTION
• Variable-length arguments

def anyFunc(name, age,*cap_letters,gender='M'):


print ("name ", name)
print ("age ", age)
print (“gender ", gender)
for s in cap_letters:
print ("capital letter: ", s)
anyFunc(‘Mack',24,('A','B'))

# the output:
Name: Mack
Age 24
gender: M
capital letter: ('A', 'B')
23

CALLING A FUNCTION
• Variable-length arguments
def any_function(**K):
print(“Data type of argument:", type(K))
print (‘K:',K)
any_function(type=‘Senior‘,Age=22)

# the output:
Data type of argument: <class 'dict'>
K: {'type': ‘Senior ‘,'Age': 22}

• *args and **kwargs are special keywords which allow function to take variable
length argument.
• *args passes variable number of non-keyworded arguments list and on which
operation of the list can be performed.
• **kwargs passes variable number of keyword arguments dictionary to function on
which operation of a dictionary can be performed.
• *args and **kwargs make the function flexible.
24

CALLING A FUNCTION
Exercise:
What are the ouputs of the following codes
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)

def countryISO_code(**code):
print (“ISO codes")
print(code)
return
#Now you can call countryISO_code function
countryISO_code(tn=“Tunisia”,de="German",en="English",fr="French")
25

GLOBAL AND LOCAL VARIABLES


Rules of global Keyword
The basic rules for global keyword in Python are:
• When we create a variable inside a function, it’s local by default.
• When we define a variable outside of a function, it’s global by default. You
don’t have to use global keyword.
• We use global keyword to read and write a global variable inside a function.
• Use of global keyword outside a function has no effect.
26

GLOBAL AND LOCAL VARIABLES


def modify(a): def modify(a): def modify(a): def small(a,b):
x=a x=x+a global x if(a<b):
#call #call x=x+a d=a
x=10 x=10 #call else:
modify(99) modify(99) x=10 d=0
print(x) print(x) modify(99) return d
print(x) #call
# the output:
print(small(9,8))
10 # the output: # the output: print(d)
UnboundLocalError 109
X is a local variable,
No impact X: we get an error message: # the output:
X is a global variable
referenced before assignment NameError: name ‘d' is not
X=10+99
defined

d: we get an error message:


Local variables of functions
can't be accessed from
outside, when the function
call has finished
27

GLOBAL AND LOCAL VARIABLES


Exercise:
What are the ouputs of the following codes

x=10 x=10 global x


def my_function(): def my_function(): x=10
x=5 global x def my_function():
print(x) x=5 x=5
return print(x) print(x)
#Now you can call the function #Now you can call the function #Now you can call the function
my_function() my_function() my_function()
print (x) print (x) print (x)
28

NESTED FUNCTION
• Python supports the concept of a nested function or inner function, which is
simply a function defined inside another function
• It is important to mention that the outer function has to be called in order for
the inner function to execute. If the outer function is not called, the inner
function will never execute.
def outer():
def outer(): x=5
x=5 def inner():
def inner(): x=10
x=10 print(‘inner’,x)
print(‘inner’,x) return
return inner()
inner() print(‘outer’,x)
print(‘outer’,x) #Now call inner function
#Now call outer function inner()
outer()
# the output:
# the output:
inner 10 # The code will return
outer 5
nothing when executed!
29

NESTED FUNCTION
def outside():
• msg is declared in the outside function and
msg = "Outside!" assigned the value "Outside!".
def inside():
msg = "Inside!" • Then, in the inside function, the value "Inside!" is
assigned to it.
print(msg)
inside()
print(msg)
outside() • When we run outside, msg has the value "Inside!" in
# the output: the inside function, but retains the old value in
Inside!
Outside!
the outside function.
• Python hasn’t assigned to the
existing msg variable, but has created a new
variable called msg in the local scope of inside.
30

NESTED FUNCTION
def outside():
• By adding nonlocal keyword to the top
msg = "Outside!" of inside, Python knows that when it sees an
def inside():
nonlocal msg assignment to msg, it should assign to the
msg = "Inside!"
print(msg) variable from the outer scope instead of
inside()
print(msg)
declaring a new variable.
outside()
# the output:
• The usage of nonlocal is very similar to that
Inside! of global, except that is used for variables in
Inside!
outer function scopes and the latter is used for
variable in the global scope.
31

NESTED FUNCTION
Exercise:
What are the outputs of the following codes

def function1(): def function1(): def function1(): def outer(num1):


x=2 x=2 x=2 def inner_increment(num1):
def function2(a): def function2(a): def function2(a): return (num1+1)
x=6 nonlocal x nonlocal x
print (a+x) num2= inner_increment(num1)
x=6 x=6
function2(3) print (a+x) print (a+x) print (num1, num2)
print (x) function2(3) print (x) #Now call outer
#Now call function1 print (x) function2(3) outer(10)
function1() #Now call function1 #Now call function1
function1() function2()
32

RECURSIVE FUNCTIONS
• Python accepts function recursion.
• Recursion is a common mathematical and programming concept.
• It means that a function calls itself. This has the benefit of meaning that you
can loop through data to reach a result.

def factorial_recursive(n):
Rules for Recursive function:
if n==1:
return 1 • It must have a base case.
else:
return n*factorial_recursive(n-1) • It must change its state and move
# Now call factorial_recursive toward the base case.
a=3
print(factorial_recursive(a))
print(factorial_recursive(5))
• It must call itself, recursively.
# the output:
6
120
33

RECURSIVE FUNCTIONS
Exercise:
What is the output of the following code
def factorial(n):
print("factorial has been called with n = " + str(n))
if n == 1:
return 1
else:
res = n * factorial(n-1)
print("intermediate result for ", n, " * factorial(" ,n-1, "): ",res)
return res
print(factorial(5))
34

PASSING BY VALUE AND BY REFERENCE


• What strategy is used in Python: call-by-value and/or call-by-reference? The correct
answer is: neither.

• Python uses a mechanism, which is known as Call-by-Object, sometimes also called Call
by Object Reference (is the more accurate way of describing it).

• In Python, everything is an object: what we commonly refer to as variables in Python are


more properly called names. Likewise, assignment is really the binding of a name to
an object.

• In Python, variables are not passed by reference or by value, they are passed
depends on the object’s type :
 If the object is mutable, then modifications to the object will persist

 If the object is immutable, then changes to the variable do not persist


35

PASSING BY VALUE AND BY REFERENCE


• Immutable objects whose value cannot change
• Tuples
• Booleans
• Numbers
• Strings
• Mutable objects whose value can change
• Dictionaries
• Lists
• User-defined objects
36

PASSING BY VALUE AND BY REFERENCE


Example:

def change_It(a): def change_Them(a,b):


a=10 a.append(5)
print(a) b[0]=6
return print(a,b)
#Now call change_It return
b=5 #Now call change_Them
print(type(b)) T1=[10]
change_It(b) T2=[15]
print(b) print(type(T1))
print(type(T2))
# the output: change_Them(T1,T2)
<class ‘int'> print(T1,T2)
10
5 # the output:
<class 'list'>
<class 'list'>
[10,5] [6]
[10,5] [6]
37

PASSING BY VALUE AND BY REFERENCE


Exercise:
What are the outputs of the following codes

def squares(list): def location(a): def AddMoney(m):


list.append(5**2) a.pop(“year”) m+=1
print(list) a[‘address’]=“Downtown” print(m)
return print(a) return
#Now call squares return #Now call AddMoney
L=[1,4,5] #Now call location Money=1000
squares(L) student = { AddMoney(Money)
print(L) “name":“Med", print(Money)
“Major":“IT",
"year":2019,
“address”: “Rades”
}
location(student)
print(student)
38

LAMBDA FUNCTION
• In Python, anonymous function is a function that is defined without a name.
• Anonymous functions are defined using the lambda keyword.
• Lambda function does not include a “return” statement, it always contains
an expression which is returned
• Anonymous functions are also called lambda functions.
• A lambda function can take any number of arguments, but can only have
one expression.
lambda arguments: expression

x =lambda a, b, c: a + b + c
print(x(5, 6, 2))

# the output:
13

x=lambda a:a** 2
print(x(5))

# the output:
25
39

LAMBDA FUNCTION WITH FILTER()


Lambda function can be used along with built-in functions like filter(), map()
and reduce().

• The filter() function in Python offers an elegant way to filter out all the
elements of a sequence and to return a new list which contains items
for which the function evaluates to True.
• The filter() method takes two arguments :
 A function - function that tests if elements of an iterable returns true or
false

 Iterable - iterable which is to be filtered, could be lists, sets, tuples, or


containers of any iterators
40

LAMBDA FUNCTION WITH FILTER()


• Example: Find the numbers divisible by thirteen from a list using anonymous
function.

my_list = [12, 65, 54, 39, 102, 339, 221,]


result = list(filter(lambda x: (x % 13 == 0), my_list))
print("Numbers divisible by 13 are",result)
# the output:
Numbers divisible by 13 are [65, 39, 221]
41

LAMBDA FUNCTION WITH MAP()


• The map() function takes two arguments a list and a function and applies a
given function to each item of a list and returns a new list of the results.

• Example: use the map() function to double all the items in a list.
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(map(lambda x: x * 2 , my_list))
print(new_list)

# the output:
[2, 10, 8, 12, 16, 22, 6, 24]

• Passing Multiple Iterators to map() Using Lambda


num1 = [4, 5, 6]
num2 = [5, 6, 7]
result = map(lambda n1, n2: n1+n2, num1, num2)
print(list(result))

# the output:
[9, 11, 13]
42

LAMBDA FUNCTION WITH MAP()


Exercise:
What is the output of the following code

def calculateSquare(n):
return n*n
numbers = (1, 2, 3, 4)
result = map(calculateSquare, numbers)
print(result)
# converting map object to set
numbersSquare = set(result)
print(numbersSquare)
43

LAMBDA FUNCTION WITH REDUCE()


• The reduce() function takes two arguments a list and a function and
performs a repetitive operation over the pairs of the list and returns a new list
of the results. This is a part of functools built-in module.

• Example:
from functools import reduce
My_list = [5, 8, 10, 20, 50, 100]
sum = reduce((lambda x, y: x + y), My_list)
print (sum)

# the output:
193
44

PART 2 – MODULES AND PACKAGES


45

WHAT ARE MODULES ?


• Modules are files containing Python definitions and statements (ex.
module_name.py)
• Modules enable you to split parts of your program in different files for
easier maintenance and better performance.
• A module is a file containing one or more function definitions that can
be shared with other programmers or projects.
• It can define functions, classes, and variables, and can also include
runnable code.
• Any Python file can be referenced as a module
46

MODULES IN PYTHON
• The modules in Python are:
• Built-in modules:
• Contain resources for certain system-specific functionalities such as OS
management, disk IO, etc.
• The standard library also contains many Python scripts (with the .py
extension) containing useful utilities.
• To display a list of all available modules, use the following command:
help(‘modules’)

• User defined modules: these are defined by the programmer.


47

BUILT-IN MODULES
• The Python interpreter has a number of built-in modules frequently used :
sys Information about Python itself (path, etc.)
platform used to access the underlying platform’s data, such as, hardware,
operating system, interpreter version information.
os Operating system functions
os.path Portable pathname tools
shutil Utilities for copying files and directory trees
cmp Utilities for comparing files and directories
glob Finds files matching wildcard pattern
re Regular expression string matching
time Time and date handling
datetime Fast implementation of date and time handling
doctest, unittest Modules that facilitate unit test
math, cmath Math functions (real and complex) faster for scalars
random Random generators (likewise)
gzip read and write gzipped files
struct Functions to pack and unpack binary data structures
StringIO, cStringIO String-like objects that can be read and written as
files (e.g., in-memory files)
types Names for all the standard Python type

48

BUILT-IN MODULES
• Example: Import and use the platform module
import platform
x = platform.system()
print(x)
# the output:
Windows

• Using the dir() and help Functions: There is a built-in function to list all the
function names (or variable names) in a module. The dir() function
• Example: List all the defined names belonging to the platform module
import platform
x = dir(platform)
print(x)
49

BUILT-IN MODULES
• Example: Import and use the os module
import os
print(os.getcwd())
#Returns the current working directory

# the output:
C:\Users\HP\PycharmProjects\MDTutorial

import os
#create a directory
os.mkdir(‘OldDir’)
import time
#The method sleep() from module time suspends execution for the given number of seconds
time.sleep(3)
#rename a file or directory
os.rename(‘OldDir’,’NewDir’)
#delete a directory
os.rmdir(‘NewDir’)
#returns the content of a directory
print(os.listdir())
50

BUILT-IN MODULES
• Example: Import and use the math module
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']
51

WORKING WITH USER DEFINED MODULES


• A module can be imported by another program to make use of its
functionality.
• A module’s definitions can be imported into other modules or into the
main module by using “import module_name”.
• Writing a module is just like writing any other Python file.
• The module’s name is available as a global variable value
52

CREATE AND USE A MODULE


To create a module just save the code you want in a file with the file
extension .py:
Example: Write function to add/subtract two numbers in a file calculation.py
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)

• Now we can use the module we just created, by using the import statement.
• To access a module’s functions, type “module_name.function_name()”
• Create another python script in the same directory with
name module_test.py and write the following code into it.
import calculation #Importing calculation module
print(calculation.add(1,2)) #Calling function defined in calculation module

# the output:
3
53

CREATE AND USE A MODULE


• Example: List all the defined names belonging to the calculation module using
the dir() and the help() functions.
import calculation
x = dir(calculation)
print(x)

# the output:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__spec__', 'add', 'sub']
54

CREATE AND USE A MODULE


• There are more ways to import modules:
• The from...import statement allows to import specific functions/variables from
a module instead of importing everything.
• In the previous example, when we imported calculation into module_test.py,
both the add () and sub() functions were imported. But what if we only
needed the add () function?
from calculation import add #Importing the add function from calculation module
print(add(1,2)) #Calling function defined in calculation module

• We can now access it directly without using the module name.


• We can import multiple attributes as well, separating them with a comma in
the import statement.
from calculation import add,sub
print(add(1,2))
print(sub(3,2))
55

CREATE AND USE A MODULE


• The from...import * statement : import all functions/attributes of a module.
from calculation import *
print(add(1,2))
print(sub(3,2))

• Re-naming an imported module:


• We can rename a module, which can be useful to give a more meaningful
name to it or the module name is too large to use repeatedly.
• You can create an alias when you import a module, by using
the as keyword:

import calculation as cal


print(cal.add(1,2))
56

VARIABLES IN MODULE
• The module can contain functions, as already described, but also
variables of all types (arrays, dictionaries, objects etc)
def add(x,y):
return (x+y)
def sub(x,y):
return (x-y)
student = {
"name": “Med",
" level": “freshman",
"age": 19,
"country": “Tunis"}

• Import the module named calculation, and access the student


dictionary:
import calculation
a = calculation.student["age"]
print(a)

# the output:
19
57

THE MODULE SEARCH PATH


• You may need your modules to be used in different programs/projects and their
physical location in the directory can be different.
• In order to use the code in a module, Python must be able to locate the module
and load it into memory. The location information is stored as paths within Python.
Whenever you request that Python import a module, Python looks at all the files in its
list of paths to find it.
• The path information comes from three sources:
• Environment variables: Python environment variables, such as PYTHONPATH, tells
Python where to find modules on disk.
• Current directory: You can change the current Python directory so that it can
locate any modules used by your application.
• Default directories: Python can still find its own libraries in the set of default
directories that are included as part of its own path information.
58

LOCATING MODULES
• When you import a module named calculation, the interpreter first searches
for a built-in module with that name. If not found, then searches for the
module in the following sequences: :
• The interpreter searches for a file named name.py in the current
directory given by variable sys.path
• If the module isn’t found, then it searches in the list of directories
specified by PYTHONPATH
• If all else fails, Python checks the default path (in UNIX -
.:/usr/local/lib/python, and in Windows c:\python20\lib)
• Script being run should not have the same name as a standard module or
an error will occur when the module is imported
59

PACKAGES IN PYTHON
• Similar, as a directory can contain sub-directories and files, a
Python package can have sub-packages and modules.

• Physically, a package is a folder containing one or more module


files

• A directory must contain a file named __init__.py in order for Python


to consider it as a package. This file can be left empty but we
generally place the initialization code for that package in this file.
60

PACKAGES IN PYTHON
• Example: Suppose we are developing a game, one possible
organization of packages and modules could be as shown in the
figure below.
IMPORTING MODULES FROM PACKAGE
• We can import modules from packages using the dot (.) operator.
Examples:
• If want to import the start module in the above example, it is done as follows.
import Game.Level.start

• If this module contains a function named select_difficulty_level(), we must use the


full name to reference it.
Game.Level.start.select_difficulty_level(2)

• we can import the module without the package prefix and call the function simply:
from Game.Level import start
start.select_difficulty_level(2)

• Another way of importing just the required function (or class or variable) form a
module within a package and then we can directly call this function :
from Game.Level.start import select_difficulty_level
select_difficulty_level(2)
PACKAGES AND MODULES
The main difference between a module and a package is that a package is a
collection of modules AND it has an __init__.py file.

myMath/ # add.py
__init__.py
def add(x, y): # sqrt.py
adv/
"""""" import math
__init__.py
sqrt.py return x + y
def squareroot(n):
add.py
""""""
subtract.py
return math.sqrt(n)
multiply.py
divide.py

# outer __init__.py import mymath


from add import add
from divide import division print mymath.add(4,5)
from multiply import multiply print mymath.division(4, 2)
from subtract import subtract print mymath.multiply(10, 5)
from adv.sqrt import squareroot print mymath.squareroot(48))
63

CONGRATULATIONS

YOU CAN NOW SAVE TIME CODING BY USING


FUNCTIONS AND MODULES

Learning is experience. I hear and I forget


Everything else is just I read and I remember
information. I do and I learn
[Albert Einstein ] [Chinese proverb]

You might also like