Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a convenience function?

In the timeit module there is the code below - what's a convenience function? I googled it and couldn't find a good answer:

def timeit(stmt="pass", setup="pass", timer=default_timer,
           number=default_number, globals=None):
    """Convenience function to create Timer object and call timeit method."""
    return Timer(stmt, setup, timer, globals).timeit(number)
like image 515
user3124200 Avatar asked Mar 05 '23 01:03

user3124200


2 Answers

It's a function that exists so you don't have to bother instantiating and keeping track of an object yourself. For example, in the timeit module, the only thing that can actually perform the functionality you want is the Timer object - but you as the programmer don't want to care about the lifecycle of that Timer, or bring it into your namespace. Hence, this timeit.timeit() function creates a Timer object relatively anonymously and calls timeit() on it, without you needing to keep track of that Timer object. It'll just do what you want it to and you don't have to worry about the details - convenience.

There are numerous other functions like this, that are essentially wrappers for instantiating a class and running a method - another example is subprocess.run(), which creates a Popen object that, again, the programmer doesn't have to keep track of.

See also the Wikipedia definition of a convenience function.

like image 62
Green Cloak Guy Avatar answered Mar 15 '23 06:03

Green Cloak Guy


Consider this:

animal_list = ["Bear", "Snake", "Snail"]
class_list = ["Mammal", "Reptile", "Gastropod"]

# Scenario 1
for i in range(len(animal_list)):
    animal = animal_list[i]
    class_ = class_list[i]
    print(f"A {animal} is a {class_}.")

# zip() - a convenience function - Scenario 2
for animal, class_ in zip(animal_list, class_list):
    print(f"A {animal} is a {class_}.")

Produced the same result:

A Bear is a Mammal.
A Snake is a Reptile.
A Snail is a Gastropod.

Scenario 1: Without the use of a convenience function

  • Clutter code; much difficult to read and understand

Scenario 2: With the use of a convenience function

  • Cleaner code and much more convenient
like image 45
Lucky Avatar answered Mar 15 '23 08:03

Lucky