WHAT IS A PYTHON MODULE


Python Module

Module is a file or library of codes or set of methods, that can be included in our Application.

How to create a module?

Creating Module-

Module can be created by saving the code in a file with the file extension .py.

Python Code- Save below code in file named mymodule.py

def warning():
   print("You are accessing mymodule")

Using Module-

We can use the module created above by using the import statement as shown in below example which import the module named mymodule and calling the method warning().

Python Code

import mymodule
mymodule.warning()

Output

You are accessing mymodule

Naming a module

A module can be named by saving file with any desired name and file extension .py

Re-naming a module

We can create an alias when we import the module by using as keyword as shown in below example that we are creating alias “mod1” for the module named “mymodule” using as keyword

Python code-

import mymodule as mod1

mod1.warning()

Output

You are accessing mymodule

Built-in Modules

We can also import the built-in modules as shown in the above examples.

HOW TO GET THE LIST OF ALL THE METHODS OR VARIABLES Names AVAILABLE IN A MODULE?

Using the dir() method

The dir() method is a built-in function to list all the function names or variable names in a module.

Python Syntax

import <module_name>
variable1=dir(<module_name>)
print(variable1)

How to import parts from modules?

We can import only required part from modules by using from keyword, syntax for the same is provided below-

from <module_name> import <part_name>

Leave a Reply

Your email address will not be published. Required fields are marked *