The other day I learned about 100 Days Of Code, which was popular on Twitter for a while. The purpose of this article is to keep a record and output how much I, as a beginner, can grow through 100 days of study. I think there are many mistakes and difficult to read. I would appreciate it if you could point out!
--Progress: Pages 48-55 ――I will write down what I often forget or didn't know about what I learned today.
Consider a program that uses the current time as the default value for keyword arguments.
from datetime import datetime
from time import sleep
def log(message, when=datetime.now()):
print('%s: %s' % (when, message))
log('Hi there!')
sleep(0.1)
log('Hi again!')
Output result
2021-01-06 14:52:16.518219: Hi there!
2021-01-06 14:52:16.518219: Hi again!
Since the keyword argument is only when the function is defined when the module is loaded, the time does not change. By setting the default value to None and documenting the actual behavior in the documentation string, you can get the correct behavior while ensuring readability.
def log(message, when=None):
"""Log a message with a timestamp.
Args:
message: Message to print.
when: datetime of when the message occurred.
Defaults to the present time.
"""
when = datetime.now()
print('%s: %s' % (when, message))
log('Hi there!')
sleep(0.1)
log('Hi again!')
Output result
2021-01-06 15:20:07.665323: Hi there!
2021-01-06 15:20:12.870457: Hi again!
When the number of function arguments increases, using positional arguments reduces readability. As an example, consider a function that has four arguments, the first two accepting an int type and the last two receiving a boolean type.
def sample(int_a, int_b, bool_c, bool_d):
# ...
sample(1, 2, True, False)
In this case, bool_c and bool_d may be easily misplaced. With keyword arguments, you don't have to worry about that. Python provides keyword-only arguments that make it impossible to specify arguments by position. ** The * symbol in the argument list indicates the end of the positional argument and the beginning of the keyword-only argument. ** **
def sample(int_a, int_b, *, bool_c, bool_d)
# ...
sample(1, 2, True, False) #Get an error
sample(1, 2, bool_c=True, bool_d=False) #Operate
Recommended Posts