0% found this document useful (0 votes)
27 views16 pages

Unit Iv

The document discusses Python modules. There are two types of Python modules: 1) built-in modules that are always available for use, and 2) user-defined modules that are created by users to simplify their projects. Built-in modules provide a wide range of functionality for tasks like mathematics, dates, file manipulation, and more. User-defined modules allow users to define reusable functions, classes, and code across multiple scripts. The document also covers how to create user-defined modules, import modules, and the different namespaces (built-in, global, local) that Python uses to manage variable scopes.

Uploaded by

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

Unit Iv

The document discusses Python modules. There are two types of Python modules: 1) built-in modules that are always available for use, and 2) user-defined modules that are created by users to simplify their projects. Built-in modules provide a wide range of functionality for tasks like mathematics, dates, file manipulation, and more. User-defined modules allow users to define reusable functions, classes, and code across multiple scripts. The document also covers how to create user-defined modules, import modules, and the different namespaces (built-in, global, local) that Python uses to manage variable scopes.

Uploaded by

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

UNIT-IV

Modules in Python:
Types of Python Modules

There are two types of python modules:

 Built-in python modules

 User-defined python modules

1. Built-in modules:

Python has a large number of built-in modules, which are used to make tasks easy and more
readable. These modules provide a wide range of functionality and are always available for
use without the need to install any additional packages.

A list of a few most frequently used built-in python modules is given below

 math: This module is very useful to perform complex mathematical functions such as
trigonometric functions and logarithmic functions.

 date: The date module can be used to work with date and time such as time, date, and
datetime.

 os: Provides a way to interact with the underlying operating system, such as reading
or writing files, executing shell commands, and working with directories.

 sys: Provides access to some variables used or maintained by the Python interpreter,
such as the command-line arguments passed to the script, the Python version, and the
location of the Python executable.

Example of built-in python modules.


# Example using the os module
import os
print(os.getcwd())
print(os.listdir())
# Example using the sys module
import sys
print(sys.version)
print(sys.argv)

# Example using the math module


import math
print(math.pi)
print(math.sin(math.pi / 2))

# Example using the json module


import json
data = {
"name": "John Doe",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
# Example using the datetime module
import datetime
now = datetime.datetime.now()
print(now)
print(now.year)
print(now.month)
print(now.day)

# Example using the re module


import re
text = "The quick brown fox jumps over the lazy dog."
result = re.search(r"fox", text)
print(result.start(), result.end(), result[0])
# Example using the random module
import random
print(random.randint(1, 100))
print(random.choice([1, 2, 3, 4, 5]))

Output:

/home/bEO6qL

['prog']

3.9.5 (default, Nov 18 2021, 16:00:48)

[GCC 10.3.0]

['./prog']

3.141592653589793

1.0

{"name": "John Doe", "age": 30, "city": "New York"}

2023-02-06 11:21:49.354873

2023

16 19 fox

17

2. User-defined modules:

User-defined python modules are the modules, which are created by the user to simplify their
project. These modules can contain functions, classes, variables, and other code that you can
reuse across multiple scripts.
How to create a user-defined module?

We will create a module calculator to perform basic mathematical operations.

# calculator.py

def add(a, b):

return a + b

def sub(a, b):

return a - b

def mul(a, b):

return a * b

def div(a, b):

return a / b

In the above code, we have implemented basic mathematic operations. After that, we will
save the above python file as calculator.py.

Now, we will use the above user-defined python module in another python program.

# main.py

import calculator
print("Addition of 5 and 4 is:", calculator.add(5, 4))

print("Subtraction of 7 and 2 is:", calculator.sub(7, 2))

print("Multiplication of 3 and 4 is:", calculator.mul(3, 4))

print("Division of 12 and 3 is:", calculator.div(12, 3))

Output:

Addition of 5 and 4 is: 9

Subtraction of 7 and 2 is: 5

Multiplication of 3 and 4 is: 12

Division of 12 and 3 is: 4.0

How to import python modules?

We can import python modules using keyword import. The syntax to import python modules
is given below.

Syntax to Import Python Modules

import module_name

Example to Import Python Modules:

import math

print(math.sqrt(4))

Output:

2.0

In the above program, we imported all the attributes of module math and we used the sqrt
function of that module.
To import specific attributes or functions from a particular module we can use keywords from
along with import.

Syntax to import python module using Attribute:

from module_name import attribute_name

Example of import python module using Attribute:

from math import sqrt

print(sqrt(4))

Output:

2.0

Now, let’s see how we can import all the attributes or functions from the module at the same
time.

We can import all the attributes or functions from the module at the same time using the *
sign.

Syntax to import python module using all Attributes:

from module_name import *

Example to import python module using all Attributes:

from math import *

print(sqrt(4))

print(log2(8))

Output:

2.0

3.0
NAMESPACE

A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of
a Python dictionary.

Real-time example, the role of a namespace is like a surname. One might not find a single
“Alice” in the class there might be multiple “Alice” but when you particularly ask for
“Alice Lee” or “Alice Clark” (with a surname), there will be only one (time being don’t
think of both first name and surname are same for multiple students).

Types of namespaces :

When Python interpreter runs solely without any user-defined modules, methods, classes,
etc. Some functions like print(), id() are always present, these are built-in namespaces.
When a user creates a module, a global namespace gets created, later the creation of local
functions creates the local namespace. The built-in namespace encompasses the global
namespace and the global namespace encompasses the local namespace.

In a Python program, there are four types of namespaces:

1. Built-In
2. Global
3. Enclosing
4. Local

These have differing lifetimes. As Python executes a program, it creates namespaces as


necessary and deletes them when they’re no longer needed. Typically, many namespaces will
exist at any given time.
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. You can list the objects in the built-in
namespace with the following command:

>>> dir(__builtins__)

['ArithmeticError', 'AssertionError', 'AttributeError',

'BaseException','BlockingIOError', 'BrokenPipeError', 'BufferError',

'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError',

'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError',

'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',

'Exception', 'False', 'FileExistsError', 'FileNotFoundError',

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.

The Python interpreter creates a global namespace for any module that our Python loads with
the import statement. To get more information, visit our Python Module.

The Local and Enclosing 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.

Example -

1. def f():
2. print('Initiate f()')

3.
4. def g():

5. print('Initiate g()')
6. print('End g()')

7. return
8.
9. g()
10.

11. print('Initiate f()')


12. return

13. f()

In the above example, the function g() is defined within the body of f(). Inside the f() we
called the g() and called the main f() function. Let's understand the working of the above
function -

o When we calls f(), Python creates a new namespace for f().


o Similarly, the f() calls g(), g() gets its own separate namespace.
o Here the g() is a local namespace created for f() is the enclosing namespace.

Each of these namespace is terminated when the function is terminated.

The lifetime of a namespace :


A lifetime of a namespace depends upon the scope of objects, if the scope of an object
ends, the lifetime of that namespace comes to an end. Hence, it is not possible to access the
inner namespace’s objects from an outer namespace.
Example:

# var1 is in the global namespace

var1 = 5

def some_func():

# var2 is in the local namespace

var2 = 6

def some_inner_func():

# var3 is in the nested local

# namespace

var3 = 7

As shown in the following figure, the same object name can be present in multiple
namespaces as isolation between the same name is maintained by their namespace.
But in some cases, one might be interested in updating or processing global variables only,
as shown in the following example, one should mark it explicitly as global and the update
or process. Note that the line “count = count +1” references the global variable and
therefore uses the global variable, but compare this to the same line written “count = 1”.
Then the line “global count” is absolutely needed according to scope rules.

# Python program processing

# global variable

count = 5

def some_method():

global count

count = count + 1

print(count)

some_method()

Output:

Scope of Objects in Python :

Scope refers to the coding region from which a particular Python object is accessible.
Hence one cannot access any particular object from anywhere from the code, the accessing
has to be allowed by the scope of the object.
Let’s take an example to have a detailed understanding of the same:
Example 1:
# Python program showing

# a scope of object

def some_func():

print("Inside some_func")

def some_inner_func():

var = 10

print("Inside inner function, value of var:",var)

some_inner_func()

print("Try printing var from outer function: ",var)

some_func()

Output:

Inside some_func

Inside inner function, value of var: 10

Traceback (most recent call last):

File "/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py", line 8, in

some_func()

File "/home/1eb47bb3eac2fa36d6bfe5d349dfcb84.py", line 7, in some_func

print("Try printing var from outer function: ",var)

NameError: name 'var' is not defined


Packages in Python:

You might also like