typing import List def summation(numbers: List) -> int: """Calculate summation of numbers""" total = 0 for number in numbers: total = total + number return total print(summation([1, 2, 3, 4, 5])) 9 / 15
Add new behaivors to a function. Default Value from typing import List def summation(numbers: List, modulo: int = 1) -> int: """Calculate summation of numbers""" total = 0 for number in numbers: total = total + number return total % modulo print(summation([1, 2, 3, 4, 5])) # No Change! print(summation([1, 2, 3, 4, 5], modulo=4)) # 15 % 5 = 3 10 / 15
Only) Force callers to supply keyword args. Keyword Only Args from typing import List def summation(numbers: List, *, modulo: int = 1) -> int: """Calculate summation of numbers""" total = 0 for number in numbers: total = total + number return total % modulo print(summation([1, 2, 3, 4, 5], modulo=5)) # 0 print(summation([1, 2, 3, 4, 5], 5)) # raise TypeError 11 / 15
is only executed a single time when the function is defined. The Same Timestamp >>> from datetime import datetime >>> from time import sleep >>> def log(message, when=datetime.now()): ... print(f"{message}: {when}") ... >>> log("Good Morning!") Good Morning!: 2017-09-03 22:20:40.786377 >>> sleep(1.0) >>> log("͓Α͏͍͟͝·͢") ͓Α͏͍͟͝·͢: 2017-09-03 22:20:40.786377 12 / 15
to Mutable Default Value. The Correct Timestamp >>> from datetime import datetime >>> from time import sleep >>> def log(message, when=None): ... when = datetime.now() if when is None else when ... print(f"{message}: {when}") ... >>> log("Good Morning!") Good Morning!: 2017-09-03 22:20:41.786424 >>> sleep(1.0) >>> log("͓Α͏͍͟͝·͢") ͓Α͏͍͟͝·͢: 2017-09-03 22:20:42.787629 13 / 15
Code", go to a bookstore and buy it. Follow the PEP 8. Consider built-in namespaces. Keyword Arguments are very powerful. Be careful of mutable default values. If you want to implement stateful functions, we recommend callable class instead of closures. References Ϧʔμϒϧίʔυ (O’Reilly Japan) Effective Python (Addison-Wesley) 15 / 15