On Thu, May 28, 2020 at 12:38 PM Greg Ewing <greg.ew...@canterbury.ac.nz> wrote:
> On 28/05/20 8:57 pm, Steven D'Aprano wrote: > > The default value used by a parameter is certainly important, and one of > > the most common reasons I call `help(func)` is to see what the default > > values are. They should be in the signature, and it is an annoyance when > > all the signature shows is that it is None, and then I have to trawl > > through screenfuls of docs, or search the web, to find out what the > > actual default is. > > I think we need a real example to be able to talk about this > meaningfully. > > But I'm having trouble thinking of one. I can't remember ever > writing a function with a default argument value that *has* to > be mutable and *has* to have a new one created on each call > *unless* the caller provided one. > > Anyone else have one? > I think the most common cases are where the default is an empty list or dict. Building on my ChainMap example from before, consider this code: ``` from collections import ChainMap c1 = ChainMap().new_child() c2 = ChainMap().new_child() c1[1] = 2 print(c1[1]) c2[1] = 3 print(c1[1]) ``` Here c1 and c2 have separate new children, so modifying c2 doesn't affect c1, so '2' is printed twice. We can simulate what would happen if a new default wasn't created each time by passing the same dict to both: ``` from collections import ChainMap m = {} c1 = ChainMap().new_child(m) c2 = ChainMap().new_child(m) c1[1] = 2 print(c1[1]) c2[1] = 3 print(c1[1]) ``` Now the second print shows '3', even though we expect that value to be in c2 but not c1.
_______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/SMHX4C2OB2A4SRPEDVWA3UVXPGZOPXWA/ Code of Conduct: http://python.org/psf/codeofconduct/