Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

An aliased import in Python utilizes the as keyword to bind an imported module, class, function, or variable to a user-defined identifier in the local namespace. This mechanism alters the local symbol table by assigning the imported object to the specified alias, while the original name remains unbound in the current scope.

Syntax

Aliasing can be applied to both absolute module imports and specific object imports from a module.

# Aliasing an entire module
import module_name as alias_name


# Aliasing a specific object from a module
from module_name import object_name as alias_name


# Aliasing multiple objects in a single statement
from module_name import object_one as alias_one, object_two as alias_two

Namespace Mechanics

When an aliased import is executed, Python performs the standard import resolution process but modifies the final binding step.
  1. Module Loading: Python searches for the module, compiles it if necessary, and loads the module object into the global sys.modules cache under its original, fully qualified name.
  2. Local Binding: Instead of binding the module or object to its original identifier in the locals() or globals() dictionary, Python binds the reference to the provided alias.
Because the original identifier is never bound in the local scope, attempting to reference it will raise a NameError.
import math as m


# The object is bound to the alias 'm'
print(m.pi)  


# The original identifier 'math' is not bound in this namespace

# print(math.pi)  -> Raises NameError: name 'math' is not defined

Submodule Aliasing

When importing a nested submodule, an aliased import binds the alias directly to the target submodule. This differs from a standard import package.submodule statement, which binds the top-level package to the local namespace and requires attribute traversal.

# Standard import: binds 'urllib' to the local namespace
import urllib.request 


# Aliased import: binds the 'request' submodule directly to 'req'
import urllib.request as req 

System Cache Behavior

Aliasing is strictly a namespace-level operation. It does not rename the module on disk, nor does it change the module’s __name__ attribute or its key in the sys.modules dictionary.
import sys
import json as j


# The local namespace recognizes the alias
print('j' in locals())        # True
print('json' in locals())     # False


# The system cache retains the original absolute name
print('json' in sys.modules)  # True
print(j.__name__)             # Outputs: 'json'
Master Python with Deep Grasping Methodology!Learn More