<jupyter_start><jupyter_text>Item 20 Use None and Docstrings to Specify Dynamic Default Arguments Sometimes None is needed as an input. If that is the case, specify in the docstring why.<jupyter_code>import datetime

# Bad
def log(when=datetime.datetime.now()):
    print(when)
    
log()
log()
log()<jupyter_output>2019-04-09 22:42:15.355098
2019-04-09 22:42:15.355098
2019-04-09 22:42:15.355098<jupyter_text>Notice that all three calls resulted in the same time. This is due the evaluation of datetime.now() happens then the function is defined.<jupyter_code># Good
def log(when=None):
    """Imagine a good docstring here."""
    when = datetime.datetime.now() if when is None else when
    print(when)

log()
log()
log()<jupyter_output>2019-04-09 22:43:58.509212
2019-04-09 22:43:58.509453
2019-04-09 22:43:58.509513<jupyter_text>This is even worse in this case (for the same reason as above)<jupyter_code>def bad_code(default={}):
    return default

bad_1 = bad_code()
bad_1[1] = 1
bad_2 = bad_code()
bad_2[2] = 25
print(bad_1)
print(bad_2)<jupyter_output>{1: 1, 2: 25}
{1: 1, 2: 25}
{'fraction_non_alphanumeric': 0.12304866850321396, 'fraction_numerical': 0.13131313131313133, 'mean_word_length': 4.989010989010989, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '606768', 'license': 'MIT', 'n_tokens_mistral': 502, 'n_tokens_neox': 410, 'n_words': 120, 'path': 'notes/Chapter_2:_Functions/Item 20 Use None and Docstrings to Specify Dynamic Default Arguments.ipynb', 'repo_name': 'johannstruongle/effective_python', 'size': '1089'}