Unit 5 Python Modules
Unit 5 Python Modules
5.1 Modules
5.2 Modules and Name-spaces
5.3 Module Import, Load and execution
5.4 Top-Down Design
5.5 Built-in name-spaces in python
What is a Module?
• Consider a module to be the same as a code library.
• A file containing a set of functions you want to include in your
application.
Module
Create a Module
To create a module just save the code you want in a file with the file extension .py:
Example :
Save this code in a file named mymodule.py
def greeting(name):
print("Hello, " + name)
Variables in Module
The module can contain functions, as already described, but also variables of all types
(arrays, dictionaries, objects etc):
a = mymodule.person1["age"]
print(a)
Scope of variable:
x = 300
def myfunc():
print(x)
myfunc()
print(x)
Namespaces in Python
• A namespace is a collection of currently defined symbolic names
along with information about the object that each name references.
You can think of a namespace as a dictionary in which the keys are the
object names and the values are the objects themselves. Each
key-value pair maps a name to its corresponding object.
• In a Python program, there are four types of namespaces:
• Built-In
• Global
• Enclosing
• Local
The Built-In Namespace
• The built-in namespace contains the names of all of Python’s built-in
objects. These are available at all times when Python is running.
The Global Namespace
• The global namespace contains any names defined at the level of the
main program. Python creates the global namespace when the main
program body starts, and it remains in existence until the interpreter
terminates.
The Local and Enclosing Namespaces
• As you learned in the previous tutorial on functions, the interpreter
creates a new namespace whenever a function executes. That
namespace is local to the function and remains in existence until the
function terminates.
Variable scope
4.Built-in: If it can’t find x anywhere else, then the interpreter tries the
built-in scope.