On Fri, Nov 2, 2018 at 7:49 PM, Steven D'Aprano <st...@pearwood.info> wrote:
> Consider the use-case where you want to pass a different default value > to the dict each time: > exactly - the "default" is per call, not the same for the whole dict. though again, how common is this? > d.setdefault(key, expensive_function(1, 2, 3)) > d.setdefault(key, expensive_function(4, 8, 16)) > d.setdefault(key, expensive_function(10, 100, 1000)) > also -- aside from performance, if expensive_function() has side effects, you may really not want to call it when you don't need to (not that that would be well-designed code, but...) and of course, you can always simply do: if key in d: val = d[key] else: val = expensive_function(4, 8, 16) d[key] = val sure, it requires looking up the key twice, but doesn't call the function unnecessarily. So it's a pretty small subset of cases, where this would be needed. defaultdict won't help, because your factory function takes no > arguments: there's no way to supply arguments for the factory. > maybe that's a feature defaultdict should have? -CHB > __missing__ won't help, because it only receives the key, not arbitrary > arguments. > > We can of course subclass dict and give it a method with the semantics > we want: > > d.my_setdefault(key, expensive_function, args=(1, 2, 3), kw={}) > > but it would be nicer and more expressive if we could tell the > interpreter "don't evaluate expensive_function(...) unless you really > need it". > > Other languages have this -- I believe it is called "Call By Need" or > "Call By Name", depending on the precise details of how it works. I call > it delayed evaluation, and Python already has it, but only in certain > special syntactic forms: > > spam and <delayed expression> > spam or <delayed expression> > <delayed expression> if condition else <delayed expression> > > There are others: e.g. the body of functions, including lambda. But > functions are kinda heavyweight to make and build and call. > > > > -- > Steve > _______________________________________________ > Python-ideas mailing list > Python-ideas@python.org > https://mail.python.org/mailman/listinfo/python-ideas > Code of Conduct: http://python.org/psf/codeofconduct/ > -- Christopher Barker, Ph.D. Oceanographer Emergency Response Division NOAA/NOS/OR&R (206) 526-6959 voice 7600 Sand Point Way NE (206) 526-6329 fax Seattle, WA 98115 (206) 526-6317 main reception chris.bar...@noaa.gov
_______________________________________________ Python-ideas mailing list Python-ideas@python.org https://mail.python.org/mailman/listinfo/python-ideas Code of Conduct: http://python.org/psf/codeofconduct/