Skip to main content

How to Use Function Aliasing in Python

In Python, functions are first-class objects, which means they can be assigned to variables, passed as arguments, and returned from other functions - just like any other value. Function aliasing takes advantage of this by creating a new name (alias) that references an existing function. Both names point to the same function object in memory.

This guide explains how function aliasing works, why it's useful, and demonstrates practical scenarios where it simplifies your code.

What Is Function Aliasing?

Function aliasing is the process of assigning an existing function to a new variable name. The alias doesn't create a copy of the function - it creates a second reference to the same function object. You can verify this using Python's built-in id() function.

def greet(name):
print(f"Hello {name}, welcome!")

# Create an alias for the greet function
welcome = greet

# Both names point to the same function object
print(f"id of greet(): {id(greet)}")
print(f"id of welcome(): {id(welcome)}")

# Both calls produce the same result
greet("Alice")
welcome("Alice")

Output:

id of greet():   139899005781152
id of welcome(): 139899005781152
Hello Alice, welcome!
Hello Alice, welcome!

Since greet and welcome share the same id, they reference the exact same function object in memory. Calling either name executes the same code.

Why Use Function Aliasing?

Function aliasing isn't just a curiosity - it has several practical applications:

  • Shortening long function names - create concise aliases for frequently used functions.
  • Improving readability - give a function a context-specific name that better describes its purpose.
  • Backward compatibility - rename a function while keeping the old name available.
  • Swapping implementations - easily switch between different functions by reassigning an alias.

Shortening Long Names

import statistics

# The full name is verbose when used repeatedly
avg = statistics.mean
dev = statistics.stdev

data = [10, 20, 30, 40, 50]

print("Average:", avg(data))
print("Std Dev:", dev(data))

Output:

Average: 30
Std Dev: 15.811388300841896
tip

This is exactly what import numpy as np or import pandas as pd does at the module level - it creates a shorter alias for the entire module. Function aliasing applies the same concept to individual functions.

Aliasing Built-in Functions

You can alias Python's built-in functions to create more descriptive names for your specific context:

# Alias built-in functions for clarity
to_int = int
to_str = str
to_list = list

print(to_int("42"))
print(to_str(3.14))
print(to_list("hello"))

Output:

42
3.14
['h', 'e', 'l', 'l', 'o']

Aliasing Methods on Objects

Function aliasing also works with methods on class instances. The alias retains its connection to the original object, so changes to the object's state are reflected through the alias.

class User:
def __init__(self, username):
self.username = username

def get_name(self):
return self.username


user = User("alice")

# Create an alias for the bound method
fetch_name = user.get_name

print(fetch_name()) # Output: alice

# Update the object's state
user.username = "bob"

# The alias reflects the change
print(fetch_name()) # Output: bob

Output:

alice
bob

The alias fetch_name is a bound method - it's tied to the specific user instance. When user.username changes, calling fetch_name() returns the updated value because it still references the same method on the same object.

Using Aliases to Swap Implementations

A powerful use of function aliasing is swapping between different implementations without changing the calling code:

def sort_ascending(data):
return sorted(data)

def sort_descending(data):
return sorted(data, reverse=True)

# Choose the sorting strategy via aliasing
sort = sort_ascending
print("Ascending:", sort([3, 1, 4, 1, 5]))

sort = sort_descending
print("Descending:", sort([3, 1, 4, 1, 5]))

Output:

Ascending: [1, 1, 3, 4, 5]
Descending: [5, 4, 3, 1, 1]
note

This pattern is a simple form of the strategy pattern, where you can dynamically change behavior by reassigning the alias.

Function Aliasing vs. Wrapping

It's important to understand the difference between aliasing and wrapping (or decorating) a function:

def original():
return "original function"

# Aliasing: same function, new name
alias = original

# Wrapping: new function that calls the original
def wrapper():
return original()

print(alias is original) # True (same object)
print(wrapper is original) # False (different object)

Output:

True
False
AliasingWrapping
Creates a new function?❌ No✅ Yes
Same object in memory?✅ Yes❌ No
Can add extra logic?❌ No✅ Yes
Performance overhead?NoneMinimal (extra function call)
Aliasing doesn't create a copy

Since an alias points to the same function object, any modifications to the function's attributes will be visible through both names:

def greet():
return "hello"

welcome = greet

# Adding an attribute to the function via one name
greet.version = "1.0"

# Visible through the alias too
print(welcome.version) # Output: 1.0

If you need an independent copy of a function, you would need to use techniques like functools.wraps or copy - but this is rarely necessary in practice.

Practical Example: Backward Compatibility

When renaming a function in a codebase, you can keep the old name as an alias to avoid breaking existing code:

def calculate_average(numbers):
"""Calculate the arithmetic mean of a list of numbers."""
return sum(numbers) / len(numbers)

# Keep the old name as an alias for backward compatibility
def compute_mean(numbers):
return calculate_average(numbers)

# Old code still works
print(compute_mean([10, 20, 30]))

# New code uses the updated name
print(calculate_average([10, 20, 30]))

Output:

20.0
20.0
note

For a simpler approach, you can just assign the alias directly:

compute_mean = calculate_average

However, using a wrapper function (as shown above) gives you the option to add a deprecation warning in the future.

Conclusion

Function aliasing in Python is a natural consequence of functions being first-class objects.

By assigning a function to a new variable, you create an alias that references the same function object in memory.

This technique is useful for shortening verbose names, improving code readability, maintaining backward compatibility, and dynamically swapping implementations.

Since aliases point to the same object, they carry no performance overhead and always stay in sync with the original function.