Thanks to visit codestin.com
Credit goes to www.tutorialsteacher.com

Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python Modules

Any text file with the .py extension containing Python code is basically a module. Different Python objects such as functions, classes, variables, constants, etc., defined in one module can be made available to an interpreter session or another Python script by using the import statement. Functions defined in built-in modules need to be imported before use. On similar lines, a custom module may have one or more user-defined Python objects in it. These objects can be imported in the interpreter session or another script.

If the programming algorithm requires defining a lot of functions and classes, they are logically organized in modules. One module stores classes, functions and other resources of similar relevance. Such a modular structure of the code makes it easy to understand, use and maintain.

Creating a Module

Shown below is a Python script containing the definition of sum() function. It is saved as calc.py.

calc.py
def sum(x, y):
    return x + y

Importing a Module

We can now import this module and execute the sum() function in the Python shell.

Example: Importing a Module
import calc 
n = calc.sum(5, 5) 
print(n)  #10
Try it

In the same way, to use the above calc module in another Python script, use the import statement.

Every module, either built-in or custom made, is an object of a module class. Verify the type of different modules using the built-in type() function, as shown below.

Example: Module Type
import calc
print(type(calc))  # <class 'module'>

import math
print(type(math))  #<class 'module'>
Try it

Renaming the Imported Module

Use the as keyword to rename the imported module as shown below.

Example:
import math as cal
n = cal.log(4) 
print(n) #1.3862943611198906
Try it

from .. import statement

The above import statement will load all the resources of the module in the current working environment (also called namespace). It is possible to import specific objects from a module by using this syntax. For example, the following module calc.py has three functions in it.

calc.py
def sum(x,y):
    return x + y

def average(x, y):
    return (x + y)/2

def power(x, y):
    return x**y

Now, we can import one or more functions using the from...import statement. For example, the following code imports only two functions in the main.py.

Example: Importing Module's Functions
from calc import sum, average
n = sum(10, 20) #30
avg = average(10, 20) #15
p = power(2, 4)  #error
Try it

The following example imports only one function - sum.

Example: Importing Module's Function
from calc import sum
n = sum(10, 20) #30

You can also import all of its functions using the from...import * syntax.

Example: Import Everythin from Module
from calc import *

n = sum(10, 20)
print(n)

avg = average(10, 20)
print(avg)

p = power(2, 4)
print(p)
Try it

Module Search Path

When the import statement is encountered either in an interactive session or in a script:

  • First, the Python interpreter tries to locate the module in the current working directory.
  • If not found, directories in the PYTHONPATH environment variable are searched.
  • If still not found, it searches the installation default directory.

As the Python interpreter starts, it put all the above locations in a list returned by the sys.path attribute.

Example: Module Attributes
import sys
sys.path
['','C:\python36\Lib\idlelib', 'C:\python36\python36.zip', 
'C:\python36\DLLs', 'C:\python36\lib', 'C:\python36', 
'C:\Users\acer\AppData\Roaming\Python\Python36\site-packages', 
'C:\python36\lib\site-packages']

If the required module is not present in any of the directories above, the message ModuleNotFoundError is thrown.

import MyModule
Traceback (most recent call last): 
File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'MyModule'

Reloading a Module

Suppose you have already imported a module and using it. However, the owner of the module added or modified some functionalities after you imported it. So, you can reload the module to get the latest module using the reload() function of the imp module, as shown below.

Example: Reloading Module
import imp
imp.reload(calc)

Getting Help on Modules

Use the help() function to know the methods and properties of a module. For example, call the help("math") to know about the math module. If you already imported a module, then provide its name, e.g. help(math).

Getting Help on Module

As shown above, you can see the method names and descriptions. It will not display pages of help ending with --More--. Press Enter to see more help.

You can also use the dir() function to know the names and attributes of a module.

Know Module Attributes and Methods

Learn about the module attributes in the next chapter.

TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.