[Python-ideas] Another use case for the 'lazy' (aka 'delayed') keyword

Chris Angelico rosuav at gmail.com
Tue Feb 28 07:19:54 EST 2017


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']

ChrisA


More information about the Python-ideas mailing list