Python: Imports and modules

nimo08

Nimo Mohamed

Posted on August 9, 2023

Python: Imports and modules

When writing scripts in Python, some definitions prove to be useful in different scripts; instead of rewriting these definitions in several files, importing modules can make this process less cumbersome.

What is a module?

  • A module is a file containing Python definitions and statements, the specific file name is simply suffixed by .py
  • Importing a module in Python allows you to access the functions, classes, variables, and other objects defined within that module for use within your Python script.

What are the contents of a module?

  • Python modules contain various objects such as functions, variables among others.
  • For example: we have module named calc; within the calc.py file we have 4 function definitions for mathematical operations i.e., add, sub, multiply, divide.
  • We can import the calc module into a script where we want to perform these mathematical operations instead of redefining them again within the script.
  • Modules contain executable statements as well, which are used to initialize the module and are run only the first time the module name is encountered in an import statement.

How to import modules

  1. import 'module': this allows access to the entire module from the script.
  2. from 'module' import 'object': using the β€˜from’ keyword allows you to access specific objects within the module i.e. from math import pi; this imports the pi variable of the math module.
  3. from 'module' import *: using the * wildcard allows access to all the names within the module except those starting with an β€˜_’; this is not recommended as it introduces an unknown set of names into the interpreter, possibly concealing some parts that you have already defined.
  4. python3 -m 'module' 'file_name': modules can be imported in the command-line as well; the -m represents the module, we then specify the module name, and the name of the file in which we want to use the module.

Module search path

  • When a module is imported e.g. calc, the interpreter first searches for a built in module with the name calc, the module names are listed in sys.builtin_module_names; if the name is not found, it proceeds to search for the calc.py in a list of directories given by the variable sys.path.

References:

πŸ’– πŸ’ͺ πŸ™… 🚩
nimo08
Nimo Mohamed

Posted on August 9, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Python: Imports and modules
python Python: Imports and modules

August 9, 2023