Unit 3
Unit 3
A module is a file containing Python definitions and statements. A module can define functions, classes,
and variables. A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use. It also makes the code logically organized. 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.
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example
def greeting(name):
print("Hello, " + name)
You can use any Python source file as a module by executing an import statement in some other Python
source file. The import has the following syntax –
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.
Now we can use the module we just created, by using the import statement:
import mymodule
mymodule.greeting("Jonathan")
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.
Variables in Module
The module can contain functions, as already described, but also variables of all types (arrays, dictionaries,
objects etc):
Example
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
Import the module named mymodule, and access the person1 dictionary:
import mymodule
a = mymodule.person1["age"]
print(a)
Naming a Module
You can name the module file whatever you like, but it must have the file extension .py
Re-naming a Module
You can create an alias when you import a module, by using the as keyword:
import mymodule as mx
Example
a = mx.person1["age"]
print(a)
Python's from statement lets you import specific attributes from a module into the current namespace.
The from...import has the following syntax −
from modname import name1[, name2[, ... nameN]]
Example
The module named mymodule has one function and one dictionary:
def greeting(name):
print("Hello, " + name)
person1 = {
"name": "John",
"age": 36,
"country": "Norway"
}
print (person1["age"])
This statement does not import the entire module mymodule into the current namespace; it just introduces
the item person1 from the module mymodule into the global symbol table of the importing module.
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.
Unit 3.1.1 Setting PYTHONPATH, Concepts of Namespace and Scope
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.
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, therefore Python assumes Money as a local variable. However, we accessed the value
of the local variable Money before setting it, so an UnboundLocalError is the result. Uncommenting the
global statement fixes the problem.
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
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. Following
is a simple example –
import math
content = dir(math)
print content
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.
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. 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 reload hello module, do the following –
reload(hello)
Greet.py
def SayHello(name):
print("Hello ", name)
function.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
That's it. We have created our package called mypackage. The following is a folder structure:
__init__.py
The package folder contains a special file called __init__.py, which stores the package's content. It serves
two purposes:
1. The Python interpreter recognizes a folder as the package if it contains __init__.py file.
Prepared by: Shreya Patel, CBPCC
Unit: 3 Python interaction with SQLite
An empty __init__.py file makes all functions from the above modules available when this package is
imported. Note that __init__.py is essential for the folder to be recognized by Python as a package. You
can optionally define functions from individual modules to be made available.
The __init__.py file is normally kept empty. However, it can also be used to choose specific functions
from modules in the package folder and make them available for import. Modify __init__.py as below:
__init__.py
The specified functions can now be imported in the interpreter session or another executable script.
test.py
Note that functions power() and SayHello() are imported from the package and not from their respective
modules, as done earlier. The output of the above script is:
D:\MyApp>python test.py
Hello world
Power(3,2)
9
Once a package is created, it can be installed for system-wide use by running the setup script. The script
calls setup() function from the setuptools module.
Save the following code as setup.py in the parent folder MyApp. The script calls the setup() function from
the setuptools module. The setup() function takes various arguments such as name, version, author, list of
dependencies, etc. The zip_safe argument defines whether the package is installed in compressed mode or
regular mode.
setup.py
url='#',
author='auth',
author_email='[email protected]',
license='MIT',
packages=['mypackage'],
zip_safe=False)
Now execute the following command to install mypackage using the pip utility. Ensure that the command
prompt is in the parent folder, in this case D:\MyApp.
Now mypackage is available for system-wide use and can be imported in any script or interpreter.
D:\>python
>>> import mypackage
>>>mypackage.average(10,20)
15.0
>>>mypackage.power(10,2)
100
SQLite3 can be integrated with Python using sqlite3 module. Python sqlite3 module adheres to Python
Database API Specification, provides a SQL interface designed to encourage and maintain the similarity
between the Python modules used to access databases. You do not need to install this module separately
because it is shipped by default along with Python version 2.5.x onwards.
Use the following steps to connect to SQLite
import sqlite3 statement imports the sqlite3 module in the program. Using the classes and methods defined
in the sqlite3 module we can communicate with the SQLite database.
Connect ()
Use the connect() method of the connector class with the database name. To establish a connection to
SQLite, you need to pass the database name you want to connect. If you specify the database file name that
already presents on the disk, it will connect to it. But if your specified SQLite database file doesn’t exist,
SQLite creates a new database for you. This method returns the SQLite Connection Object if the connection
is successful. You can specify filename with the required path as well if you want to create a database
anywhere else except in the current directory.
Connect To Database
Prepared by: Shreya Patel, CBPCC
Unit: 3 Python interaction with SQLite
Following Python code shows how to connect to an existing database. If the database does not exist, then it
will be created and finally a database object will be returned.
import sqlite3
conn = sqlite3.connect('test.db')
You can change your path as per your requirement. Keep the above code in sqlite.py file and execute it as
shown below. If the database is successfully created, then it will display the following message
execute()
The execute() methods run the SQL query and return the result. This routine executes an SQL statement.
The SQL statement may be parameterized.
Create a Table
Following Python program will be used to create a table in the previously created database.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.close()
When the above program is executed, it will create the COMPANY table in your test.db and it will display
the following messages –
INSERT Operation
Following Python program shows how to create records in the COMPANY table created in the above
example.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
conn.commit()
print "Records created successfully";
conn.close()
When the above program is executed, it will create the given records in the COMPANY table and it will
display the following two lines –
SELECT Operation
Following Python program shows how to fetch and display records from the COMPANY table created in the
above example.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
When the above program is executed, it will produce the following result.
ID = 2
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
UPDATE Operation
Following Python code shows how to use UPDATE statement to update any record and then fetch and display
the updated records from the COMPANY table.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
When the above program is executed, it will produce the following result.
ID = 2
Prepared by: Shreya Patel, CBPCC
Unit: 3 Python interaction with SQLite
NAME = Allen
ADDRESS = Texas
SALARY = 15000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
DELETE Operation
Following Python code shows how to use DELETE statement to delete any record and then fetch and display
the remaining records from the COMPANY table.
import sqlite3
conn = sqlite3.connect('test.db')
print "Opened database successfully";
When the above program is executed, it will produce the following result.
Opened database successfully
Total number of rows deleted : 1
ID = 1
NAME = Paul
ADDRESS = California
SALARY = 20000.0
ID = 3
NAME = Teddy
ADDRESS = Norway
SALARY = 20000.0
ID = 4
NAME = Mark
ADDRESS = Rich-Mond
SALARY = 65000.0
import sqlite3
conn = sqlite3.connect('D:\SQLite3\sqlite3\item_dist.db')
c = conn.cursor()
rows = c.fetchall()
row in rows:
print(row)
#print(rows)
conn.close()
fetchone()
When you want to read only one row from the SQLite table, then you should use fetchone() method of a
cursor class. You can also use this method in situations when you know the query is going to return only one
row.
import sqlite3
conn = sqlite3.connect('D:\SQLite3\sqlite3\item_dist.db')
c = conn.cursor()
print(c.fetchone())
conn.close()