if statement, with function inside it: if (t = Test()) == True:

Terry Reedy tjreedy at udel.edu
Mon May 4 18:36:55 EDT 2009

Antoon Pardon wrote:
> On 2009-04-24, Steven D'Aprano <steve at REMOVE-THIS-cybersource.com.au> wrote:
>> On Fri, 24 Apr 2009 03:00:26 -0700, GC-Martijn wrote:
>>> Hello,
>>> I'm trying to do a if statement with a function inside it. I want to use
>>> that variable inside that if loop , without defining it.
>>> def Test():
>>>     return 'Vla'
>>> I searching something like this:
>>> if (t = Test()) == 'Vla':
>>>     print t # Vla
>>> or
>>> if (t = Test()):
>>>     print t # Vla
>> Fortunately, there is no way of doing that with Python. 

There is a way to do something close.

def x(v):
     x.val = v
     return v

if x(3)==3:
     print('x.val is ', x.val)
# prints
x.val is  3

In OP's case, condition is "x(Test()) == 'Vla'"

>> This is one  source of hard-to-debug bugs that Python doesn't have.
> I think this is an unfortunate consequence of choosing '=' for the
> assignment.

Actually, is is a consequence of making assignment a statement rather 
than an expression.  And that is because if assignment were an 
expression, the new name would have to be quoted.  Or there would have 
to be a special exception to the normal expression evaulation rule.  In 
other words, the problems one sees in a pure expression language.  Note 
that C, for instance, which has such a special exception, does not, last 
I knew, allow a,b = 1,2.

The solution for this use case is to encapsulate the binding within a 
function.  The above is one possible example.  One could use a pocket 
class instead of a pocket function.  Or

def set_echo(name, val):
   globals()[name] = val
   return val

if set_echo('t', Test()) == 'Vla': print t ...

Terry Jan Reedy

More information about the Python-list mailing list