[Python-ideas] Combining test and assignment

Chris Rebert pyideas at rebertia.com
Sun Jan 22 05:11:46 CET 2012

On Sat, Jan 21, 2012 at 8:05 PM, Eike Hein <sho at eikehein.com> wrote:
> On 1/22/2012 4:48 AM, Nick Coghlan wrote:
>> Simple embedded assignment, though, only works when the predicate is
>> just "bool" - as soon as the condition differs from the value you want
>> to access, you need to revert to the existing idiom *anyway*. Given
>> the non-trivial costs of adding new syntax, that gets the idea put
>> into the "not worth the hassle" bucket.
> I thought a bit about what Python offers today in terms
> of built-in tools to approximate what I want. My first
> thought was to try and abuse context managers, but aside
> from being horribly ugly, a with statement also can't
> prevent its body from being run, it seems.
> Another, possibly better way is to modify locals(), i.e.:
> if test(expr, 'var'):
>   ... do stuff ...
> Where the test function returns the expression but also
> stores its results in locals()['var'].

That doesn't actually work (unless you happen to be writing code in
module-level scope, where globals are locals):
http://docs.python.org/library/functions.html#locals :
"Note: The contents of this dictionary should not be modified; changes
may not affect the values of local and free variables used by the


More information about the Python-ideas mailing list