Skip to content

Aliasing Module Names as Keyword Python How-To Guide

Updated: at 03:01 AM

Importing modules is a fundamental concept in Python programming that allows you to access code from another file. By importing a module, you can utilize the functions, classes, and other code constructs defined in that module.

However, sometimes the module name may be long or confusing. Aliasing the module name using the as keyword provides a convenient way to shorten the name and improve readability of your code.

This comprehensive guide will explain what aliasing module names means in Python and why it is useful. It covers the syntax for aliasing modules using the as keyword, best practices for choosing alias names, and examples of aliasing built-in and third-party modules. Additionally, it discusses advanced usage like nesting aliased imports and aliasing module contents.

By the end, you will have a deep understanding of aliasing module names in Python and how to effectively utilize this technique in your own projects. Let’s get started!

Table of Contents

Open Table of Contents

What is Aliasing Module Names?

Aliasing module names refers to importing a module under a different name using the as keyword in Python. This allows you to shorten the module name to something more convenient and readable in your code.

For example, instead of:

import very_long_module_name

very_long_module_name.some_function()

You can alias it like:

import very_long_module_name as vlm

vlm.some_function()

Now the module is imported as vlm rather than its full name very_long_module_name.

The as keyword renames the module during the import process. Every usage of the full module name is replaced by the alias name.

Why Alias Module Names?

There are a few key reasons why you may want to alias module names in Python:

In summary, aliasing leads to more readable, convenient code by simplifying usage of imported modules. It is a best practice recommended by Python style guides like PEP 8.

Syntax for Aliasing Module Names

The syntax for aliasing a module name during import is simple:

import module_name as alias_name

For example:

import numpy as np

This does a normal import of the numpy module, but makes the alias np available instead of numpy in your code.

You can alias module names whether you use import module_name or from module_name import syntax.

import long_module_name as lmn
from module import some_function as sf

You can import multiple modules in one statement and alias each one:

import module1 as m1, module2 as m2

And you can chain aliases:

import very_long_module as vlm
import vlm as v

The initial as alias is carried through, so now v points to the very_long_module.

Choosing Good Alias Names

When deciding on an alias name, aim for these qualities:

For example, good aliases:

import numpy as np # widely used alias
import matplotlib.pyplot as plt # common convention
import my_machine_learning_utils as ml # clear abbreviation

Bad aliases:

import numpy as n # too short, ambiguous
import matplotlib.pyplot as mp # overlaps with math.pi
import my_machine_learning_utils as m # meaningless

Some tips for creating great aliases:

Examples of Aliasing Common Modules

Let’s look at some examples of aliasing popular built-in and third-party Python modules:

Built-in Modules

For long or generic built-in module names like math, sys, and re, aliasing can help avoid name conflicts and improve readability:

import math as mathlib
import sys as system
import re as regex

You can then write clear code like:

from mathlib import sin
print(system.argv)
regex.search('(')

NumPy

The NumPy numerical library is commonly imported as np [1]:

import numpy as np

array = np.random.rand(5,5)

This follows widespread convention and avoids excessive typing of numpy.

Pandas

The Pandas data analysis library is generally imported as pd [2]:

import pandas as pd

df = pd.DataFrame(data)

Again this reduces keystrokes when repeatedly accessing Pandas functionality.

Matplotlib

For the Matplotlib graphing library, plt is the standard alias [3]:

import matplotlib.pyplot as plt

plt.hist(data)
plt.show()

This is shorter and more readable than the full matplotlib.pyplot path.

Tensorflow

For Tensorflow machine learning, tf is commonly used [4]:

import tensorflow as tf

model = tf.keras.Sequential()

This is much more convenient than typing the full tensorflow each time.

As you can see, aliasing cleans up usage of popular libraries. Check documentation for recommended aliases.

Advanced Usage of Aliased Imports

Let’s discuss some more advanced aliasing techniques and best practices.

Nesting Aliased Imports

You can nest aliased imports to further organize modules:

import long_module as lm
import lm.utils as u
import lm.plots as p

Now the lm submodules can be accessed via u and p.

Just be sure to retain clarity and consistency across your codebase.

Aliasing Specific Module Contents

When using from module import item syntax, you can directly alias the imported names:

from math import sin as sine, cos as cosine

This provides control over each name brought into your code’s namespace.

Re-exporting Aliased Names

Say you have:

import long_module as lm

You can re-export lm’s attributes under different names:

from lm import func1 as f1, func2 as f2

This brings specific elements of lm into your code’s namespace as f1 and f2.

Avoid Name Collisions

Take care to avoid alias name collisions which can cause odd bugs:

# BAD, sin redefined!
from math import sin
import numpy as np
np.sin(x) # Error, numpy sin overrides math.sin

# GOOD, no more name collision
from math import sin as sine
import numpy as np
sine(x) # Uses math.sin
np.sin(x) # Uses numpy sin

So be mindful of scopes when aliasing!

Summary

To recap, aliasing module names using the as keyword is a useful Python technique that:

The key points to remember are:

Aliasing improves the clarity, concision, and maintainability of your Python code. Use this guide to start utilizing aliases effectively in your own imports.

Happy Python programming!