BTW, going back to the question of mutable defaults, it occurs to me > that there is an "obvious" idiom for self-documenting sentinels for > defaults that are deferred because you want a new instance each time > the function is called: use the constructors! Here are some empty > mutables: > > def foo(x=list): > if x == list: > x = x() > > def bar(x=dict): > if x == dict: > x = x() > > And here's a time-varying immutable: > > import datetime > def baz(x=datetime.datetime.now): > if x == datetime.datetime.now: > x = x() > > I guess this fails more or less amusingly if the constructor is > redefined. Of course any callable object could be the sentinel. It > doesn't need to be a type or a factory function for this device to > work. However, I don't see a use case for that generality. > > Steve >
I like this a lot. And for those who are on board iwth type hinting, seems like you could indicate your intentions pretty clearly by saying something like: def foo(x: Constructing[List] = list): if x == list: x = x() A Constructing[List} being a thing whose type is supposed to be a list if provided by the user, and the final type is also list if not provided by the user.
_______________________________________________ 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/HVWSEGVHH5QCMJYKRW4BGQ2RXUFGQA7O/ Code of Conduct: http://python.org/psf/codeofconduct/