<div dir="auto">Well you could just use a dict subclass here with get() that takes callable...</div><div class="gmail_extra"><br><div class="gmail_quote">On Feb 28, 2017 14:25, "Michel Desmoulin" <<a href="mailto:desmoulinmichel@gmail.com">desmoulinmichel@gmail.com</a>> wrote:<br type="attribution"><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><br>
<br>
Le 28/02/2017 à 13:19, Chris Angelico a écrit :<br>
> On Tue, Feb 28, 2017 at 11:04 PM, Michel Desmoulin<br>
> <<a href="mailto:desmoulinmichel@gmail.com">desmoulinmichel@gmail.com</a>> wrote:<br>
>> Instead, I think it's a good example of were 'lazy' could help. You<br>
>> can't get simpler than:<br>
>><br>
>> conf.get('setting_name', lazy load_from_db('setting_name'))<br>
>><br>
><br>
> Alternatively, you could define 'conf' as a subclass of dict with a<br>
> __missing__ method:<br>
><br>
> class Config(dict):<br>
>     def __missing__(self, key):<br>
>         self[key] = load_from_db(key)<br>
>         return self[key]<br>
> conf = Config()<br>
><br>
> Then it becomes even simpler AND less redundant:<br>
><br>
> conf['setting_name']<br>
<br>
Yes but this assumes:<br>
<br>
- I have access to the code instantiating conf;<br>
- all code using conf are using load_from_db as a default value;<br>
- load_from_db exists for all code using the conf object<br>
<br>
There is always a solution to all problems, as Python is turing complete.<br>
<br>
You don't need list comprehension, you can use a for loop.<br>
<br>
You don't need upacking you can uses indexing.<br>
<br>
And you don't need lazy, it's just convenient.<br>
______________________________<wbr>_________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" rel="noreferrer" target="_blank">https://mail.python.org/<wbr>mailman/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" rel="noreferrer" target="_blank">http://python.org/psf/<wbr>codeofconduct/</a><br>
</blockquote></div></div>