Aliases
Explore the concept of aliases in Python to understand how different variables can reference the same object, including functions. Learn how this underpins functional programming and the implications of redefining functions during execution.
We'll cover the following...
Aliasing
Aliasing is when two different variables reference the same object in Python. For example, consider this code:
We assign a tuple value to variable t in line 1. This means that t holds a reference to the tuple object. The tuple itself is stored in memory somewhere.
When we set u = t in line 2, we are actually copying the reference into the variable, u. We don’t create a copy of the actual tuple itself. There is only one tuple, but both t and u point to it, so we call them aliases – different names for the same data. When we then print t[2] and u[2], they both refer to the element at index 2 in the original tuple.
In the earlier example, we saw that square is just a variable that holds a reference to a function object – a function that calculates the square of x. We can create an alias for that, too:
In this case, sq can be used in place of square, doing exactly the same thing, because they both point to the same underlying object – a function object.
This also works with built-in functions. For example, you could create an alias of print, as shown here:
Of course, just because you can, doesn’t mean you should! This might seem like a great way of shortening your code if you use a lot of print statements, but it is likely to be quite confusing to anyone reading it.
In fact, you are quite unlikely to use aliases directly in your code, but you will use them indirectly quite often. In the previous example, with square, we pass the variable, a, into square, but within the function, it is aliased as x.
In the next lesson, we will look at passing functions into other functions as parameters, and they will be aliased in a similar way. This is the essential feature of Python that makes functional programming possible at all.
Redefining a function
Since functions are essentially variables that happen to hold function objects, you can reassign them at any time, as shown below.
Python has no problem with this. But it has consequences and, generally, is best avoided. Here is a simple example of what can happen:
We have defined a function, a, that prints 1. We then define function b that calls function a that prints 1. When we call b for the first time, it prints 1 as expected.
Next, we redefine a to print 2 instead. What happens when we call b again?
Well, as far as function b is concerned, a is just a global variable. It looks up the value of a, which is a function object. In fact, it is now the function that prints 2. b calls that function, and 2 is printed.
The pitfall here is that you have changed the behavior of function b without it being particularly obvious what has happened, which is a recipe for bugs. It is rarely a good thing to do.