import Statement

A major advantage of Python as a programming language is the availability of a plethora of pre-developed modules and packages. Whether it’s a mathematical operation, date and time operation, or complex data manipulation, there is a Python module catering to the needs of developers. Modules and packages provide well-tested, reusable code that saves both time and effort. But how do you access this wealth of resources within your Python script? This is where the import statement comes into play in Python.

What is the import Statement?

The import statement in Python is used to load other Python source code files in your program so you can access their functions, methods, classes, and variables. Basically, it gives your script access to the Python code you want from another module or package, without you having to write it yourself.

Here is an example of how to use the import statement:

1import math
2print(math.pi)

In the example above, the import statement is used to import the ‘math’ module, and then we have accessed the value of ‘pi’ defined in that module.

Importing Specific Attributes

The import statement can also be used with the Python’s dot notation, to import specific attributes or functions from a module:

1from math import pi
2print(pi)

Here, we specifically import the ‘pi’ attribute from the ‘math’ module.

Importing Multiple Modules

The import statement allows loading multiple modules by separating them with commas:

1import math, datetime, sys
2print(math.pi)
3print(datetime.date.today())
4print(sys.version)

Note that importing many modules in one line is generally discouraged for readability reasons.

Importing and Renaming

In some cases, the name of the module or attribute you are importing might be too long, and you may prefer a shorter alias. Python’s import statement also allows you to rename what you import:

1import datetime as dt
2print(dt.date.today())

The as keyword allows you to provide an alias to the imported module.

Note

Always capitalize on the modular approach of Python, but be careful not to import unnecessary modules as it can slow down your script.

Did you know?

The import statement only executes a module’s code the first time it’s imported. If you change a module and want those changes to be reflected in your script, you need to restart your Python interpreter.