[Python-ideas] Combining test and assignment (original) (raw)
Eike Hein sho at eikehein.com
Sun Jan 22 05:05:48 CET 2012
- Previous message: [Python-ideas] Combining test and assignment
- Next message: [Python-ideas] Combining test and assignment
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.
Actually, just to be clear, in the use case I had in mind spam() is returning a numeric value. That satisfies a truth test and is still useful in other ways (but I assume you are actually on the same page, hence the quotation marks around bool).
Another case I come across frequently is with the re module, where re.match() returns either None or a MatchObject.
if re.match(pattern, string) as m: ... make use of the match object ...
Anyway, thank you for a comprehensive reply and recap of the history.
To date, nobody has been interested enough in the latter idea to put together a formal PEP and reference implementation for python-dev's consideration, and the former idea has been informally rejected several times due to the lack of generality.
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'].
I wonder if a function like this (with a better name obviously) would have a place in the stdlib somewhere, or is it too much of a limited-use hack?
Cheers, Nick.
-- Best regards, Eike Hein
- Previous message: [Python-ideas] Combining test and assignment
- Next message: [Python-ideas] Combining test and assignment
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]