KEMBAR78
Modules | PDF | Namespace | Scope (Computer Science)
0% found this document useful (0 votes)
40 views12 pages

Modules

The document explains Python modules and packages, emphasizing their role in organizing code for better maintainability. It covers how to create and import modules, use the from-import statement, and manage namespaces in Python. Additionally, it details the structure of packages and how to import modules from them, providing examples throughout.

Uploaded by

Priksha Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views12 pages

Modules

The document explains Python modules and packages, emphasizing their role in organizing code for better maintainability. It covers how to create and import modules, use the from-import statement, and manage namespaces in Python. Additionally, it details the structure of packages and how to import modules from them, providing examples throughout.

Uploaded by

Priksha Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Python Modules

As our program grows bigger, it may contain many lines of code. Instead of putting everything in a single
file, we can use modules to separate codes in separate files as per their functionality. This makes our
code organized and easier to maintain.

Module is a file that contains code to perform a specific task. A module may contain variables,
functions, classes etc.

Create a simple Python module

Let’s create a simple file1.py in which we one add and another subtract.

define two functions,

Program in File1.py

def add(x, y): print(x+y)

def subtract(x, y): print(x-y)

Importing a module

Import Module in Python (import the entire module)

Import in python is similar to #include header_file in C/C++. Python modules can get access to code
from another module by importing the file/function using import. The import statement is the most
common way of invoking the import machinery, but it is not the only way.

We can import the functions, and classes defined in a module to another module using the import
keyword in some other Python source file. When the interpreter encounters an import statement, it
imports the module if the module is present in the search path.

import

We use the keyword to do this. To import our previously defined module example, we type the following
in the Python prompt.

Syntax of Python Import

import module_name

Note: This does not import the functions or classes directly instead imports the module only. To access
the functions inside the module the dot(.) operator is used.

import file1 file1.add(10, 2) output:

12

The from-import Statement in Python

Python’s from statement lets you import specific attributes from a module without importing the
module as a whole.
Importing specific attributes from the module

Here, we are importing specific sqrt and factorial attributes from the math module.(math module is
built-in module that you can use for mathematical tasks.)

Program:

from math import sqrt, factorial, log, pow, sin, cos sqrt(16)

factorial(6) log(10) pow(2,3) sin(1)

cos(1)

Output:

4.0

720

2.30

0.84

0.54

From import * Statement

The use of * has its advantages and disadvantages. If you know exactly what you will be needing from
the module, it is not recommended to use *, else do so.

Program:

from math import * sqrt(16) factorial(6)

Output:

4.0

720

Import with alias(Renaming the Imported Module in Python)

You can rename the module you are importing, which can be useful in cases when you want to give a
more meaningful name to the module or the module name is too large to use repeatedly. You can use
the as keyword to rename it. The following example explains how to use it in your program.

import calculation as cal

print(cal.add(1,2))
Module for displaying Fibonacci series

fibseries.py

def fib(n):

a=0 b=1 sum=0

for i in range(0,n):

print(sum, end=” ”) a=b

b=sum

sum=a+b

open python shell and import above module and access the function

import fibseries

fibseries.fib(10)

output: 0 1 1 2 3 5 8 13 21 34

Namespace in Python

A namespace is a way of providing the different name for each object in Python. Everything in Python is
an object, i.e., a variable or a method. In other words, it is a collection of the defined symbolic names
along with the information about the object that each name references. A namespace can be
understood as a dictionary where a name represents a key and objects are values. Let's understand it
with a real-life example

- A namespace is like a surname. A "Karthikeya" name might be difficult to find in the class if there are
multiple "karthikeya," but when we particularly ask for "govinda karthikeya" or "surla venkata karthikeya,".
It might be rare to find the same name and surname in a class for multiple students.

The namespace helps the Python interpreter to understand what exact method or variable is trying to
point out in the code. So its name gives more information - Name (which means name, a unique
identifier)

+ Space (related to scope).Python doesn’t have same name of objects within single scope.
In Python, there are four types of namespaces which are given below.

o Built-in

o Global

o Enclosing

o Local

As these namespace various have lifetimes, Python interpreter creates namespaces as necessary and
deletes them when they are no longer needed.

Let's understand the various types of namespace in Python.

1. The Built-in Namespace

As its name suggests, it contains pre-defined names of all of Python's built-in objects already available
in Python. Let's list these names with the following command.

Open the Python terminal and type the following command.

Command - dir( builtins )

The built-in namespace creates by the Python interpreter when its starts up. These are terminated when
Python interpreter terminates.

2. The Global Namespace

The global namespace consists of any names in Python at any level of the main program. It is created
when the main body executes and remains in existence until the interpreter terminates.

3. The Local Namespaces

The function uses the local namespaces; the Python interpreter creates a new namespace when the
function is executed. The local namespaces remain in existence until the function terminates. The
function can also consist of another function. We can define one function inside another as below.

Program for global and local namepaces:

def evenodd(num): #global namespace n=num #local namespace


if n%2==0:

return "even no"

else:

return "odd no "

num=int(input("enter no:")) print(evenodd(num))


Module built-in functions

dir() function in Python

dir() is a powerful inbuilt function in Python3, which returns list of the attributes and methods of any
object (say functions , modules, strings, lists, dictionaries etc.)

Syntax :

dir({object}) Returns :

dir() tries to return a valid list of attributes of the object it is called upon. Also, dir() function behaves
rather differently with different type of objects, as it aims to produce the most relevant one, rather than
the complete information.

• For Class Objects, it returns a list of names of all the valid attributes and base attributes as well.

• For Modules/Library objects, it tries to return a list of names of all the attributes, contained in that
module.

• If no parameters are passed it returns a list of names in the current local scope.

Example : Without importing external libraries.

print(dir())

output:

[' builtins__', ' cached__', ' doc__', ' file ', ' loader ' ' name ','__package ', ' spec ']

Example2 : With importing external libraries Import math

Import random

print(dir())

output:

[' builtins__', ' cached__', ' doc__', '__file__', ' loader ', ' name ', '__package ', ' spec ', 'math', 'random']

Python Packages

We usually organize our files in different folders and subfolders based on some criteria, so that they can
be managed easily and efficiently. For example, we keep all our games in a Games folder and we can
even subcategorize according to the genre of the game or something like this. The same analogy is
followed by the Python package.

A Python module may contain several classes, functions, variables, etc. whereas a Python package can
contains several module. In simpler terms a package is folder that contains various modules as files.
Creating Package

Let’s create a package named “world” that will contain two modules “india.py” and “america.py”. To
create this module follow the below steps –

• Create a folder named “world”.

• Inside this folder create an empty Python file i.e. init .py

• Then create two modules “india.py” and “america.py” in this folder.

India.py

def delhi():

print(“I am from delhi”)

def shimla():

print(“I am from shimla”)

america.py

def alabama():

print(“I am from alabama”)

def washington():

print(“I am from washington”)

Understanding init .py

init .py helps the Python interpreter to recognise the folder as package. It also specifies the resources
to be imported from the modules. If the init .py is empty this means that all the functions of the modules
will be imported

import Modules from a Package

We can import these modules using the from…import statement and the dot(.) operator.

Syntax:

import package_name.module_name

Example: Import Module from package

We will import the modules “india.py” and “america.py” from the above created package i.e., “world”
and will use the functions inside those modules.

Import world.india

Import world.america

world.america.alabama() #output: I am from alabama

world.india.delhi() #output: I am from delhi

You might also like