User defined modules in python

Best post on user defined modules in python-3

Before we explain user defined modules let’s have glims on ‘what are modules?’.

Python has extensive libraries for supporting various functionalities like graphical user interface, database connectivity, mathematical calculations etc.

A file which consists of a collection of related functions is called as a module.

Python has many built-in modules like math, time, random etc.

Python also allows user to define its own modules according to the requirement such modules are called as user defined modules.

To use or call these modules in our script we use specific keywords like import and from.

In this post we will be studying math, time and random module in detail along with user defined modules.

What are user defined modules?

Python allows us to create and import our own module with desired functionalities.

To create a module of our choice we must first decide the functionalities required and choice the name of the module accordingly.

To create a module first step after deciding the module name is to create a file in python and save it with an extension of “.py”.

Keyword should not be use as a module name.

Whenever you create a module in it can be called in any other file using “import” keyword.

It is important run “module_name.py” i.e. file or module created by us before calling it in another script.

If we call our user defined module in any file without executing the module or file it will generate and import error.

Источник

Python Modules

For example: In Test.py , where the test is the module name.

In Python, large code is divided into small modules. The benefit of modules is, it provides a way to share reusable functions.

Table of contents

Types of modules

In Python, there are two types of modules.

Built-in modules

Built-in modules come with default Python installation. One of Python’s most significant advantages is its rich library support that contains lots of built-in modules. Hence, it provides a lot of reusable code.

Some commonly used Python built-in modules are datetime , os , math , sys , random , etc.

User-defined modules

The modules which the user defines or create are called a user-defined module. We can create our own module, which contains classes, functions, variables, etc., as per our requirements.

How to import modules?

In Python, the import statement is used to import the whole module. Also, we can import specific classes and functions from a module.

For example, import module name .

When the interpreter finds an import statement, it imports the module presented in a search path. The module is loaded only once, even we import multiple times.

To import modules in Python, we use the Python import keyword. With the help of the import keyword, both the built-in and user-defined modules are imported. Let’s see an example of importing a math module.

import math # use math module functions print(math.sqrt(5)) # Output 2.23606797749979

Import multiple modules

If we want to use more than one module, then we can import multiple modules. This is the simplest form of import statement that we already used in the above example.

Syntax of import statement:

import module1[,module2[. moduleN]
# Import two modules import math, random print(math.factorial(5)) print(random.randint(10, 20)) 

Import only specific classes or functions from a module

To import particular classes or functions, we can use the from. import statement. It is an alternate way to import . Using this way, we can import individual attributes and methods directly into the program.

In this way, we are not required to use the module name. See the following example.

Syntax of from. import statement:

# import only factorial function from math module from math import factorial print(factorial(5))

Import with renaming a module

If we want to use the module with a different name, we can use from..import…as statement.

It is also possible to import a particular method and use that method with a different name. It is called aliasing. Afterward, we can use that name in the entire program.

Syntax of from..import ..as keyword:

Example 1: Import a module by renaming it

import random as rand print(rand.randrange(10, 20, 2)) 

Example 2: import a method by renaming it

# rename randint as random_number from random import randint as random_number # Gives any random number from range(10, 50) print(random_number(10, 50)) 

Import all names

If we need to import all functions and attributes of a specific module, then instead of writing all function names and attribute names, we can import all using an asterisk * .

Syntax of import * statement:

from math import * print(pow(4,2)) print(factorial(5)) print(pi*3) print(sqrt(100))
16.0 120 9.42477796076938 10.0

Create Module

In Python, to create a module, write Python code in the file, and save that file with the .py extension. Here our module is created.

def my_func(): print("Learn Python with PYnative")
Learn Python with PYnative

Variables in Module

In Python, the module contains Python code like classes, functions, methods, but it also has variables. A variable can list , tuple , dict , etc.

Let’s see this with an example:

First, create a Python module with the name test_module.py and write the below code in that file.

cities_list = ['Mumbai', 'Delhi', 'Bangalore', 'Karnataka', 'Hyderabad']

Now, create a Python file with the name test_file.py , write the below code and import the above module test_module.py in that file. See the following code.

import test_module # access first city city = test_module.cities_list[1] print("Accessing 1st city:", city) # Get all cities cities = test_module.cities_list print("Accessing All cities :", cities)

When we execute this test_file.py , the variable of test_module.py is accessible using the dot (.) operator.

Accessing 1st city: Delhi Accessing All cities : ['Mumbai', 'Delhi', 'Bangalore', 'Karnataka', 'Hyderabad']

Python Module Search Path

When we import any program module, the interpreter first searches for a specified name for a built-in module. If the name is not found, the interpreter searches in a list of directories given by the variable sys.path which initialized from the environment variable PYTHONPATH .

PYTHONPATH have the same syntax as the Unix shell variable PATH, list of the colon(:)-separated directory names. When a PYTHONPATH is not set, or the file is not found there, the search continues in an installation-dependent default path. It is usually /usr/local/lib/python .

Reloading a module

In Python, when we import a module in our program using the import statement, the module is loaded. By default, the module loaded only once, even if we import it multiple times.

Sometimes we update the loaded module with new changes, then an updated version of the module is not available to our program. In that case, we can use the reload() function to reload a module again.

First, create a Python module with the name test_module.py and write the below code in that file.

Now, create a Python file with the name, test_file.py and write the below code in it and import the module test_module.py . See the following code.

import time from importlib import reload # load 1st time import test_module time.sleep(20) # reload reload(test_module) time.sleep(20) # reload again reload(test_module) print("This is test file..")
Welcome to PYnative Welcome to PYnative Welcome to PYnative This is test file..

The dir() function

In Python, dir() is a built-in function. This function is used to list all members of the current module. When we use this function with any object (an object can be sequence like list , tuple , set , dict or can be class, function, module, etc. ), it returns properties, attributes, and method.

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

Syntax of dir() function:

['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']

Return value from dir()

  • When we use dir() with an object, it returns the list of the object’s attributes.
  • When we use the __dir__() The object’s method, if that object has this method, it returns all attributes of that object. And if that object does not has __dir__() method, it returns all information about that object.
  • If we do not pass an object to dir() it returns a list of currently available functions, methods, properties, attributes, names in the local scope.

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Python – Modules

A Python module is basically a file that contains Python code. The Python standard library contains thousands of functions distributed throughout the modules.

User-defined Module

The user-defined module is written by the user at the time of program writing.

How to create a User-defined Module?

To create a module just write a Python code in a file with file extension as .py:

Program (1): To demonstrate how to create a module in a file with extension as module_name.py in Python.

def accept_int(): val = int(input("Please enter any integer integer: ")) print('The integer value is', val)

How to access a User-defined Module?

Now we will access the module that we created earlier, by using the import statement.

Program (1): To demonstrate how to import the module in Python.

Please enter any integer integer: 22 The integer value is 22

Explanation: for Output

Access Standard Functions using import keyword

In Python Programming user place import keyword in the statement with module name to use the corresponding library function. In general, all similar types of library functions are grouped under one module means to say library functions like pow(), sin(), etc. all are used for performing the mathematical operation defined in only math module.

General Form (Syntax):

The syntax to access standard functions using import keyword is given below,

from module import function1_name, function2_name. function_name

where, import keyword is used to access the function1_name, function2_name, ….function_name from the module.

The statement in python is given by

from math import sqrt, pow

Explanation:

  • sqrt represent function1_name and pow represent function2_name
  • math is the module.
  • import is a keyword.

Program (1): To demonstrate how to access standard functions using import keyword.

from math import sqrt,pow # input number the user num = float(input("Enter number: ")) # Calculate the square root root = sqrt(num) # display result print("Square root of", num, " https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-8445020960232859" crossorigin="anonymous"> 

Program (1): To demonstrate how to access standard functions without import keyword.

# display text as python prgramming print("python prgramming")

Explanation

  • The print function exists in a module named __builtins__ so we can directly access the program.

Python – Numbers After reading the Python Numbers topic, you will understand numbers and its classification as float,…

Python – Lambda expressions After reading this Python lambda expression or function topic, you will understand how to implement it…

Python – Variable After reading this Python Variable topic, you will understand how to create and manipulate Variable,…

Python – Type Casting After reading this Python type casting topic, you will know its theory, examples, you will…

Python – JSON After reading this Python JSON topic, you will understand how to convert JSON to Python…

Published by

Electrical Workbook

We provide tutoring in Electrical Engineering. View all posts by Electrical Workbook

Источник

Читайте также:  Python получить массив значений словаря
Оцените статью