[Python-ideas] Another use case for the 'lazy' (aka 'delayed') keyword
Michel Desmoulin
desmoulinmichel at gmail.com
Tue Feb 28 07:24:36 EST 2017
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.
More information about the Python-ideas
mailing list