[Python-ideas] switch statement as context manager?
Mathias Panzenböck
grosser.meister.morti at gmx.net
Mon Feb 10 22:25:50 CET 2014
See: https://gist.github.com/panzi/8924450
But again, I don't recommend to use this. Just to demonstrate what is already possible with the most simple constructs.
Am 2014-02-10 19:14, schrieb Mathias Panzenböck:
> You don't need a context manger here:
>
> switch = lambda value: lambda other: value == other
>
> case = switch(foobar)
> if case(1): pass
> if case(2): pass
>
>
> But I don't think this is at all useful. Maybe if case does something more complex than == (e.g. isinstance for classes
> and matching of regular expressions etc.). But than it's a bit of black magic. What if value and other both are classes
> or regular expressions?
>
> Other version:
>
> case = foobar.__eq__
> if case(1): pass
> if case(2): pass
>
> Am 2014-02-10 15:31, schrieb Sturla Molden:
>> I've noticed that PyExt has a switch statement implemented as a context
>> manager.
>>
>> with switch(foobar):
>> if case(1): pass
>> if case(2): pass
>>
>> Would this be something to consider for the standard lib, e.g. contextlib?
>>
>> Sturla
>>
> _______________________________________________
> 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