Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of giving an alias to an builtin function in Python

Tags:

python

I was reading the code of Python headq.merge and it seem like they're creating alias for builtin function like _len = len. Just wondering what's the purpose of that?

Thanks a lot!

like image 291
Bubble Bubble Bubble Gut Avatar asked Apr 11 '18 15:04

Bubble Bubble Bubble Gut


People also ask

What is function aliasing in Python?

In Python, aliasing happens whenever one variable's value is assigned to another variable, because variables are just names that store references to values.

How do you assign an alias to a function in Python?

In contrast to a normal Python method, an alias method accesses an original method via a different name—mostly for programming convenience. An example is the iterable method __next__() that can also be accessed with next() . You can define your own alias method by adding the statement a = b to your class definition.


1 Answers

The context is that they are assigning a global name to a local name inside the function:

def merge(*iterables):
    ...
    _len = len
    ...

The expectation is that _len will be used many times, and accessing a local name is faster than repeatedly looking up a global name. Whether this makes a significant difference in the overall runtime can only be determined by benchmarking your code.

like image 50
chepner Avatar answered Sep 20 '22 09:09

chepner