Basic Import

The fundamental syntax for importing a module in Python is as follows:

import module_name

Here, module_name is the name of the module you want to import. When you use this basic import syntax, you are essentially bringing the entire module into your program. This means that you can access the contents of the module using the module_name. syntax.


import math
result = math.sqrt(25)

In this example, we import the math module and then use it to calculate the square root of 25.

Learn More

Selective Import

  • from module_name import function_name

    While importing entire modules is convenient, it may lead to unnecessary overhead if you only need specific functions, classes, or variables from a module. To address this, Python provides the capability for selective imports: In this case, module_name is still the name of the module you want to import, and function_name is the name of the function or class you want to import. This method directly imports from the module only the parts you specify. This makes your code more efficient and well-organized.

  • The Role of PYTHONPATH

    The PYTHONPATH environment variable plays a pivotal role in Python's ability to locate and import modules and packages. It is a list of directories that Python will search through when you use an import statement. Python searches these directories in the order they are listed in PYTHONPATH, and when it finds a matching module or package, it imports it into your program. Understanding how PYTHONPATH works is essential, as it allows you to control the locations from which Python can import modules. This can be particularly useful when you have custom modules or packages that you want to use in your projects. To view the current value of your PYTHONPATH, you can execute the following Python code: import sys print(sys.path) This code will display a list of directories that Python checks when you use import statements.

  • Standard Library Imports

    Python's standard library is a treasure trove of modules and packages that come pre-installed with Python. These modules cover a wide range of functionalities, such as mathematical operations, file handling, datetime manipulation, and much more. Importing modules from the standard library is straightforward and requires no additional installations. Here are some examples of standard library imports:

Importing the math Module

The math module provides a variety of mathematical functions and constants. You can import it as follows: import math After importing math, you can use functions like math.sqrt(), math.sin(), and constants like math.pi in your code. Importing the datetime Module The datetime module allows you to work with dates and times. You can import specific classes or functions from the module like this: from datetime import datetime, date, time This line of code allows you to access datetime functions like and directly.