[Python-ideas] with expression

Yann Kaiser kaiser.yann at gmail.com
Thu Feb 20 22:32:04 CET 2014


On 20 February 2014 20:54, Andrew Barnert <abarnert at yahoo.com> wrote:
> On Feb 20, 2014, at 10:50, Yann Kaiser <kaiser.yann at gmail.com> wrote:
>
>> In the use case of providing a default value, if the default value is
>> the product of an expensive operation, an alternative context manager
>> can be designed to compute the value only when needed, for instance:
>>
>>    fa = factorials[n] with SetDefault(factorials, n, lambda: math.factorial(n))
>
> This one is less useful. That SetDefault has to repeat the factorials and n references, and it makes that fact explicit to the reader, and writes the same thing in two different ways.
>
> But, more importantly, a simple "setdefault" function that did the same thing as your SetDefault class without the context management would be easier to write, and both nicer and easier to use:
>
>     fa = setdefault(factorials, n, lambda: math.factorial(n))
>

Agreed. I was asked in the other thread for a way to defer evaluation
for the default value, which can simply be done by swapping the
context manager. It boils down to:

    x = func() with ProduceDefault(lambda: expensive_func(), SomeException)

I still can't come up with an example that doesn't ask for simply
caching the expensive calculation, or where the cheap version's domain
can't be checked beforehand. It may be possible that the
"ProduceDefault" use case simply does not exist, but ultimately it is
something that can be user-implemented at the python programmer's
whim. Maybe someone will come up with a tangible use case for that
particular aspect, but there are other aspects to an inline "with", as
we've both noted.



-yk

>> Other examples using existing context managers:
>>
>>    contents = f.read() with open('file') as f
>
> This probably buys you more in a context where a statement doesn't work just as well, like a function parameter, or a lambda callback:
>
>     self.read = Button('Read', command=lambda: dostuff(f) with open(path) as f)
>
> But either way, it's something I've wanted before.
>
>>    with open('file') as f:
>>        contents = f.read()
>>
>>
>>
>>    d = Decimal(1) / Decimal(7) with Context(prec=5)
>>
>>    with Context(prec=5):
>>        d = Decimal(1) / Decimal(7)
>>
>> I think that's all I can think of so far. Sorry as this might be a
>> little too detailed to start with, so I will remind you there is no
>> offense in rethinking any of what I posted here.
>>
>> -yk
>> _______________________________________________
>> 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/


More information about the Python-ideas mailing list