2.5. Function#
2.5.1. Omit Else Clauses in a Python Function to Improve Code Readability#
If you are using if statements to return different values, adding an else clause may introduce unnecessary complexity. Omitting the else clause for the last condition will make the code simpler and easier to read.
def get_discount(price):
if price >= 100:
return 20
if price >= 50:
return 10
else: # not necessary
return 5
def get_discount(price):
if price >= 100:
return 20
if price >= 50:
return 10
return 5 # omit else
2.5.2. When to Use and Not to Use Lambda Functions#
Lambda functions are helpful when defining a function that is used only once and does not require a name.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# use lambda function because it is used only once
even_numbers = filter(lambda num: num % 2 == 0, numbers)
However, if you need to reuse a function in various parts of your code, use a named function to avoid repeating the same code.
# use named function because it is used multiple times
def is_even(num: int):
return num % 2 == 0
even_numbers = filter(is_even, numbers)
any(is_even(num) for num in numbers)
True
2.5.3. **kwargs: Pass Multiple Arguments to a Function in Python#
Sometimes you might not know the arguments you will pass to a function. If so, use **kwargs
.
**kwargs
allow you to pass multiple arguments to a function using a dictionary. In the example below, passing **{'a':1, 'b':2}
to the function is similar to passing a=1
, b=1
to the function.
Once **kwargs
argument is passed, you can treat it like a Python dictionary.
parameters = {'a': 1, 'b': 2}
def example(c, **kwargs):
print(kwargs)
for val in kwargs.values():
print(c + val)
example(c=3, **parameters)
{'a': 1, 'b': 2}
4
5
2.5.4. Decorator in Python#
Do you want to add the same block of code to different functions in Python? If so, try decorator.
In the code below, I created the decorator to track the time of the function say_hello
.
import time
def time_func(func):
def wrapper():
print("This happens before the function is called")
start = time.time()
func()
print('This happens after the funciton is called')
end = time.time()
print('The duration is', end - start, 's')
return wrapper
Now all I need to do is to add @time_func
before the function say_hello
.
@time_func
def say_hello():
print("hello")
say_hello()
This happens before the function is called
hello
This happens after the funciton is called
The duration is 0.0002987384796142578 s
Decorator makes the code clean and shortens repetitive code. If I want to track the time of another function, for example, func2()
, I can just use:
@time_func
def func2():
pass
func2()
This happens before the function is called
This happens after the funciton is called
The duration is 4.38690185546875e-05 s