[Python-ideas] Another use case for the 'lazy' (aka 'delayed') keyword
Michel Desmoulin
desmoulinmichel at gmail.com
Tue Feb 28 07:04:51 EST 2017
The debate on the 'lazy' keyword seems to have settled, but I don't know
if somebody is trying to write a PEP about it.
Anyway, I was doing something like this the other day:
conf.get('setting_name', load_from_db('setting_name'))
And then realized I could save a query not doing the load_from_db() call
most of the time.
But dict.get didn't accept callable so I couldn't do:
conf.get('setting_name', lambda key: load_from_db('setting_name'))
Which is standard practice in a lot of popular Python libs on Pypi.
Instead I did:
val = conf.get('setting_name')
if val is None:
val = load_from_db('setting_name')
Which is way more verbose. It also has a bug if None is a valid
configuration value or if I expect my code to be thread safe.
It was not a problem for me, but in that case one would even have to do:
try:
val = conf['setting_name']
except KeyError:
val = load_from_db('setting_name')
Which is even more verbose.
I was going to suggest to python-ideas to update the dict.get()
signature to accept a callable, but it would break compatibility with
many code actually getting a callable.
We could do it for Python 4, but it's far way.
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'))
More information about the Python-ideas
mailing list