[Python-ideas] Another use case for the 'lazy' (aka 'delayed') keyword
Markus Meskanen
markusmeskanen at gmail.com
Tue Feb 28 07:27:32 EST 2017
Well you could just use a dict subclass here with get() that takes
callable...
On Feb 28, 2017 14:25, "Michel Desmoulin" <desmoulinmichel at gmail.com> wrote:
>
>
> Le 28/02/2017 à 13:19, Chris Angelico a écrit :
> > On Tue, Feb 28, 2017 at 11:04 PM, Michel Desmoulin
> > <desmoulinmichel at gmail.com> wrote:
> >> Instead, I think it's a good example of were 'lazy' could help. You
> >> can't get simpler than:
> >>
> >> conf.get('setting_name', lazy load_from_db('setting_name'))
> >>
> >
> > Alternatively, you could define 'conf' as a subclass of dict with a
> > __missing__ method:
> >
> > class Config(dict):
> > def __missing__(self, key):
> > self[key] = load_from_db(key)
> > return self[key]
> > conf = Config()
> >
> > Then it becomes even simpler AND less redundant:
> >
> > conf['setting_name']
>
> Yes but this assumes:
>
> - I have access to the code instantiating conf;
> - all code using conf are using load_from_db as a default value;
> - load_from_db exists for all code using the conf object
>
> There is always a solution to all problems, as Python is turing complete.
>
> You don't need list comprehension, you can use a for loop.
>
> You don't need upacking you can uses indexing.
>
> And you don't need lazy, it's just convenient.
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170228/5fc6817b/attachment-0001.html>
More information about the Python-ideas
mailing list