If you want to run small Python code snippets, using the Python interpreter is your best bet. However, after quitting the interpreter, when you go back, all the functions, variables, etc. that were defined earlier get lost. That’s the reason why there is a need for Python scripts. It is used to write programs to store the code for as long as you want and run them multiple times without getting them lost. Then, it is vital to prepare this file and pass this file as input to the interpreter.

However, as the programs cross thousands of lines of code and get bigger, it becomes difficult to maintain them and locate the functions or variables that you want to use. Also, since different functions serve different purposes, it is always better to group those functions which serve similar purposes. This enhances the readability of the overall program. If you want to use a function that you had written earlier in a program, without actually copying its definition, it would prove to be much easier.

The Ultimate Ticket to Top Data Science Job Roles

Post Graduate Program In Data ScienceExplore Now
The Ultimate Ticket to Top Data Science Job Roles

What Are Python Modules?

To achieve this ease, Python allows you to pack all the similar functions or variable definitions in a single file and allows you to use them in any other Python script or interpreter later on. Such files in Python are called modules. You can import functions or variables from a module directly using the import statement into other modules or scripts. 

A module in Python contains tons of statements and function definitions. For any script to be a module, you need to make sure that the file name is the name of the module, and the file has an extension of .py. Inside the module, you can access the name of the module which is stored automatically as a global variable called __name__. Let’s understand this with the help of an example.

How to Create and Use Python Modules?

Now, it’s time to create a module called fibonacci.py where you will define two functions that will compute the Fibonacci series up to a range given as the argument. 

# This is a module for Fibonacci Series

def fibonacci1(count):    # This function is used to print Fibonacci Series

   i = 0

   j = 1

   while i < count:

       print(i, end=', ')

       i, j = j, i+j

   print()

 def fibonacci2(count):   # This function is used to return Fibonacci Series

   fibo = []

   i = 0

   j = 1

   while i < count:

       fibo.append(i)

       i, j = j, i+j

   return fibo

Here, in this module, you have defined two functions called fibonacci1 and fibonacci2. The first one directly prints the result, and the second returns a list containing the series. 

Let’s open the Python interpreter and try to import this module using the following command.

>>> import Fibonacci

PythonModules_1

Make sure you are in the same directory which contains your Python module.

Next, let’s calculate the Fibonacci series up to a range of 1000 using both the functions defined in it. You will use the dot operator to call the method from the module.

>>> Fibonacci.fibonacci1(1000)

>>> Fibonacci.fibonacci2(1000)

PythonModules_2

Let’s try to print the name of the module.

>>> Fibonacci.__name__

PythonModules_3

How to Import From Python Modules?

You have already seen the import statement and how to import functions or variables from a Python module in the previous example. Before you move ahead and discuss a few of its variations, let’s look at some important points as well. 

A Python module can contain both function definitions as well as some executable statements. The executable statements are used to initialize the respective Python modules. They will be executed as soon as there is an import from the module or the module itself is run as a script and will be executed only once. 

Moreover, each Python module has a symbol table associated with it, which can be used by all the functions inside that module. Hence, without having concerns about clashes with the overall global variables, the users can use the global variables in the modules using the simple dot notation (Fibonacci.variable_name).

Also, you can import other pre-defined as well as user-defined modules inside the modules as well. It is considered as a kind of ritual, however, it’s not mandatory that you define the import statement at the beginning of each script or module. The names of the modules that you import are defined inside the symbol table of the current module. 

Now, you’ll look at some other variants of the import statement in Python modules.

You can import particular functions or items from a module using the following syntax. It includes only the names of the imported items in the current module’s symbol table.

>>> from Fibonacci import fibonacci1, fibonacci2

>>> fibonacci1(1000)

PythonModules_4

Another variant imports all the items from the module if you use the asterisk (*) symbol along with the import statement. This will import all the items from the modules except those items that begin with an underscore. Generally, it is not preferred because it introduces unknown names and probably hides other important things.

>>> from Fibonacci import *

>>> fibonacci1(1000)

PythonModules_5 

How to Name or Rename Python Modules?

Naming a Python module is simple. You can name them whatever you want. Just make sure that the file name ends with .py extension. As already discussed, as soon as you create a Python module, the name of the Python modules is stored inside a variable called __name__ present inside the module.

If you want to rename a Python module while importing it, you can use the ‘as’ keyword. It simply creates an alias for the imported module and is bound directly to it.

For example,

>>> import Fibonacci as fib

>>> fib.fibonacci2(1000)

PythonModules_6 

You can also use the ‘as’ keyword when using the ‘from’ keyword to import modules.

>>> from Fibonacci import fibonacci2 as fib2

>>> fib2(1000)

PythonModules_7 

The above statements import the fibonacci2 function from the Fibonacci module and give it an alias called fib2.

Please note that in order to make the execution efficient, each Python module is imported only once in an interpreter session. Hence, if you change the modules in the middle of the session, you need to restart the interpreter. 

How to Execute Python Modules as Scripts?

It is possible to execute Python modules as scripts using the following command.

$ python3 Fibonacci.py <arguments>

It will execute the codes inside the module in the same way you would import it and run it in other scripts. However, the only change will be the __name__ variable will be changed to the __main__ variable. This implies that you can simply put the below code snippet at the end of the module to execute it as a script. Then, it can be both used as a script and a module. 

if __name__ == "__main__":

   import sys

   fibonacci1(int(sys.argv[1]))

Here, it is mentioned that if you run this module as a script and pass the arguments, then the argument will be passed into the fibonacci1 function, and the function will be called, and it will return the values or print it. After putting the snippet at the end of the module, run the following command inside the terminal.

PythonModules_8

You can see that the 1000 argument is passed into the fibonacci1 function inside the Fibonacci module and the result is printed.

However, if you import the module, it won’t run the script.

PythonModules_9.

What Are Variables in Python Modules?

So far, this article has discussed how one can define functions inside Python modules and then import them inside scripts. You can define variables inside Python modules as well and import them the same way as you would import functions. Let’s define a dictionary variable inside a module called Students.py. 

student1 = {

   "name": "Rachel",

   "Age": 31,

   "Gender": "Female"

}

Here, there is a variable called student. It’s a dictionary variable that contains information related to the name, age, and gender of the students.

Let’s try to import it and access the student’s name.

>>> import Students

>>> Students.student1["name"]

PythonModules_10

How to Locate Python Modules?

When you use the import statement to import a module either in the interpreter, or a Python script, or another module, then the interpreter searches for the imported module in the mentioned sequence.

  1. Firstly, it searches for a built-in module of that name.
  2. In case the interpreter does not find a built-in module of that name, it then looks out for this file in the directory list given by the variable called sys.path. 

To check out the list of directories inside the variable sys.path, you can use the following piece of code.

>>> import sys

>>> sys.path

PythonModules_11 

The variable called sys.path is initialized from a bunch of locations. The first one is the directory that contains the script which imports the module or the current directory. The next one is the PYTHONPATH variable which contains a list of directories that follow the same syntax as the PATH variable. And the final one is the default installation-dependent.

After the initialization process, the programs can modify the sys.path variable. The directory which has the script, is placed at the top of the search path, even before the standard library path, which means that instead of loading scripts with the same name from the standard library, scripts from that directory will be loaded. 

The PYTHONPATH is just an env variable that consists of a list of directories and can be set using the following commands for Windows and Linux specifically.

set PYTHONPATH = c:\python20\lib;

set PYTHONPATH = /usr/local/lib/python

Become a Certified Expert in AWS, Azure and GCP

Caltech Cloud Computing BootcampExplore Program
Become a Certified Expert in AWS, Azure and GCP

Namespaces and Scope in Python Modules

In Python modules, variables are identifiers that map particular objects. There are namespaces in Python modules that are just dictionaries containing these variable names as keys and the objects that they point to as values.

When executing a statement, they can access the variables from local as well as global scopes. If the variables are the same in local as well as global scope, then the local variable shadows the global ones. In Python, functions and class methods have their own local namespaces. This might cause confusion. When you want to access a global variable inside a function, you need to explicitly mention that you want to use the global variable. Or else, it will define the same variable inside the local namespace of the function. 

To do this, you can use the keyword called global. Once encountered this statement, it stops searching the local namespace for the variable with that same name. Let’s consider the example below.

count = 20

def addCount():

   global count

   count = count + 1

 addCount()

print(count)

In the above program, the addCount() function, instead of defining its own local variable called count and incrementing it, looks for the same variable in the global namespace since you have used the global keyword. 

PythonModules_12

You can also use the locals() and globals() functions to return the dictionaries containing the names of variables in local and global namespaces. If you call the locals() method from within a particular function, it returns variables in local namespaces. For globals() method, it will return the global namespace variable even if you call it from within a function. They return dictionaries.

To return all the names, modules, variables, functions that are defined within a module, you can use the built-in dir() method. Consider the example below.

# This is a module for Fibonacci Series

def fibonacci1(count):    # This function is used to print Fibonacci Series

   i = 0

   j = 1

   while i < count:

       print(i, end=', ')

       i, j = j, i+j

   print()

 def fibonacci2(count):   # This function is used to return Fibonacci Series

   fibo = []

   i = 0

   j = 1

   while i < count:

       fibo.append(i)

       i, j = j, i+j

   return fibo

For the above Fibonacci module, let’s try to use the dir() method.

PythonModules_13 

What Are built-in Python Modules?

Apart from the custom modules that you build, Python offers a ton of standard built-in modules that can be used to serve a variety of purposes. For example, Python provides the built-in Math module which can be used to perform important mathematical computations such as finding degrees, exponents, factorial, sin, cosine values, etc. You can use the random built-in module to generate a stream of random numbers. You can use a built-in datetime module to print the current date and time stamps. Let’s understand these with the help of an example.

import math

print("The value of pi is: ", math.pi)

print("The value of 5 radians in degrees is: ", math.degrees(5))

print("The square root of 100 is: ", math.sqrt(100))

print("The factorial of 5 is: ", math.factorial(5))

import random

#This prints random integer between 10 and 20

print(random.randint(10, 20))

#This prints random integer between 0 and 100

print(random.random()*100)

from datetime import *

# This will convert the number of sec to date object

print(date.fromtimestamp(3600))

PythonModules_14. 

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Wrapping Up!

To conclude, in this article, you saw in detail, what Python Modules are, and how you can leverage them to reduce the complexities of the program, and increase efficiency. You looked into how you can create, use, import, name, and rename Python modules with hands-on examples. Moving ahead, this article discussed what variables are in the Python modules, and how Python locates modules. Further on, you saw how Python programs utilize namespaces and scoping to resolve naming issues and at last, you saw a few helpful built-in Python modules.

We certainly hope that with the help of this article, you will now be able to create efficient Python modules and reduce the overall complexity of your programs! If this tutorial has gotten you interested in learning more about Python, Simpilearn’s Python Certification Course should be your next learning destination. From shell scripting to data operations, conditional statement and Django, this comprehensive certification course will teach all you need to get a practical work-ready understanding of Python and set you up on a career as a Python expert.

If you have any inputs or need any clarification on this python modules tutorial, feel free to write to us in the comments section below. Our experts will review your comments and respond promptly to them.

Happy Coding!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Automation Test Engineer

Cohort Starts: 17 Apr, 2024

11 Months$ 1,499
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449