0

Often I need to use the value returned by a function only if such value satisfy a condition, as in this construct:

tmp = my_func(x)
if tmp == some_value:
    # do something with tmp

I'd like to make this code more concise and readable by avoiding to use a new variable tmp, similarly to this way:

if my_func(x) == some_value:
    # do something with my_func(x) last return

Another example could be:

tmp = initialization_value
while tmp != some_value:
    tmp = my_func(x)
    # do something with tmp
    # change value of x

that would be more concise and readable as

while my_func(x) != some_value:
    # do something with my_func(x) last return
    # change value of x

Is it possible to obtain or implement such coding style?

FOLLOW UP

It seems to me that the best way to obtain it is by means of a decorator caching last returned vaue, see answer below.

Ultimate and definitive solution

Despite this question got no votes, it seems that I was not the only one to ask for such a language feature, in fact finally Python 3.8 introduced the walrus operator, which addresses this need exactly. With Python 3.8+ the above code would be written very conveniently as:

if (result := my_func(x)) == some_value:
    # do something with result
1
  • This is a deliberate design decision. The pain of writing tmp twice is balanced out by the lack of = accidents.
    – Katriel
    Dec 4, 2012 at 11:22

5 Answers 5

2

No, you cannot assign in an if statement. Your initial code is fine.

3
  • 1
    The repetition of tmp annoys me.
    – mmj
    Dec 4, 2012 at 11:05
  • 1
    @mmj: Sorry it does. But it is not a temporary variable, since you use it in a if statement, then return it.
    – Martijn Pieters
    Dec 4, 2012 at 11:06
  • I was used to Lisp which can partly avoid that through functional paradigm and setf.
    – mmj
    Dec 4, 2012 at 11:09
1

It is valid to write:

if my_func(x) == some_value:
    # do something 
    return something

But if you want to use the result of my_func(x) inside the if statement you would have to recompute it, thus your way of doing it is fine.

1
  • Check my solution by means of a decorator.
    – mmj
    Dec 7, 2012 at 9:49
1

Your solution is :

def save_last(f):
    def w(*args, **kwargs): # w is the 'wrapper' function
        w.last=f(*args, **kwargs)
        return w.last
    return w

@save_last
def fync(x): # just an example function
    if 1<x<100: return (x%15 + x//6)*(x%2)
    else: return (x%10)*10 + (x%7)
print 'fync.__dict__ :',fync.__dict__

for i in xrange(1,114):
    if fync(i)%7==3:
        print 'fync(%3d)==%2d   %2d-3==%2d==7*%d' \
              % (i,fync.last,fync.last,
                 fync.last-3,(fync.last-3)//7)
print 'fync.__dict__ :',fync.__dict__

result

fync.__dict__ : {}
fync(  3)== 3    3-3== 0==7*0
fync(  9)==10   10-3== 7==7*1
fync( 35)==10   10-3== 7==7*1
fync( 41)==17   17-3==14==7*2
fync( 79)==17   17-3==14==7*2
fync( 85)==24   24-3==21==7*3
fync(102)==24   24-3==21==7*3
fync(109)==94   94-3==91==7*13
fync(113)==31   31-3==28==7*4
fync.__dict__ : {'last': 31}

.

I find the use of a decorator a heavy way while it can be done like this:

def finc(x):
    if 1<x<100: finc.last = (x%15 + x//6)*(x%2)
    else: finc.last = (x%10)*10 + (x%7)
    return finc.last
print 'finc.__dict__ :',finc.__dict__

for i in xrange(1,114):
    if finc(i)%7==3:
        print 'finc(%3d)==%2d   %2d-3==%2d==7*%d' \
              % (i,finc.last, finc.last,
                 finc.last-3,(finc.last-3)//7) 
print 'finc.__dict__ :',finc.__dict__ 

The result is exactly the same.

.

By the way, I imagined the following solution:

def func(x=None,li=[None]):
    if x is None: return li[0]
    elif x>0:
        if 1<x<100:  li[0] = (x%15 + x//6)*(x%2)
        else: li[0] = (x%10)*10 + (x%7)
        return li[0]

for i in xrange(1,114):
    if func(i)%7==3:
        print 'func(%3d)==%2d   %2d-3==%2d==7*%d' \
              % (i,func(),func(),
                 func()-3,(func()-3)/7)

The result is evidently the same.
But I prefer the above solution, resorting to an attribute wihout using a decorator.

.

Nota Bene

The principle of all the three solutions is the same: storing the result in the function, either in an attribute or in a default argument list, before returning it.

That's moving the creation of name from the outside of the function to the inside of the function:
anyway, it is necessary to have an object that stores the result somwhere, an attribute or a list, and consequently to have also a dedicated name to keep access to the storing object.
That's just moving the problem.

.

EDIT

By the way, my last solution, with a list internal to the function, isn't so far from the following another soution:

L = []

def fonc(x,li=L):
    if 1<x<100:  li[:] = [(x%15 + x//6)*(x%2)]
    else: li[:] = [(x%10)*10 + (x%7)]
    return li[0]

for i in xrange(1,114):
    if fonc(i)%7==3:
        print 'func(%3d)==%2d   %2d-3==%2d==7*%d' \
              % (i,L[0],L[0],
                 L[0]-3,(L[0]-3)/7)

But this solution is nearly equivalent to what you wrote in your question: keeping the result of the function thanks to a binding to a tmp identifier or keeping the result as an element of a list doesn't make a lot of difference.

So I'm still on my first opinion, your problem is a false problem:

  • either you need to do something of the result of a function and you are obliged to keep it as an object referenced through one name, inside or outside the function

  • or you doesn't have to do something with the result of the function and then you can simply write:

.

if my_func(x) == some_value:
    # do nothing with my_func(x)
    return some_value
6
  • First of all I'd like point out that I think mine is a legitimate issue. In fact, in case the condition is not satisfied, each time you have this common case construct, you have in code the creation of a new variable which is totally unused, and I want to avoid just this, in order to make the code more concise and clear. (Of course the alternative 'solution' of calling the function more than once is excluded 'a priori'.)
    – mmj
    Feb 6, 2014 at 8:41
  • About your 1st solution, what I don't like is that you need to change the definition of EACH function you want to add the feature to. This is a repetion that blatantly violates the DRY rule. If you want many functions to have the feature, your code will be greatly burdened. A decorator instead is defined once and may be applied to any function without affecting its definition; code repetitions are avoided altogether.
    – mmj
    Feb 6, 2014 at 8:41
  • Same about your 2nd and 3rd solution, they affect the internal definition of each function you want to add the feature to. I agree with you that that in all the solutions, mine included, the problem in some way is just 'moved', because we need anyway a place in memory where to store the last result of the function, but the point of my question is how to do that in a manner that makes the code more simple, concise and clear, and in this respect the decorator seems to me the best way until now.
    – mmj
    Feb 6, 2014 at 8:41
  • I agree with you. I thought that the use of a decorator is the way to employ when there are several functions to call, but I thought this only after having posted my answer. - Now I understand that your only aim is to obtain a script the more simple, concise a clear as possible. It's legitimate. - I personally have an oriented-mind: I take attention to the efficiency, I always think about the operations performed under the hood. From this point of view, I fear that the use of a decorator weighs the underlying process.
    – eyquem
    Feb 6, 2014 at 14:00
  • Is the process: 1/ call of func then call of save_last ? I mean: under the hood. That is to say two code objects, in fact. Or is the process only one call?: 2/ func, after having been defined and transformed by the decorator, is a function having a code object as if it would have been defined as in my first code. That is to say, only one code object. - In case 1, two code objects are successively activated at each call. In second case, only one code object activated only once. - I don't know if I am clear, and even if what I write has a real sense. I'm not good in Python enough.
    – eyquem
    Feb 6, 2014 at 14:08
0

If you have this construct quite often, you can do

def cmp_iter(a, b):
    if a == b:
        yield a
# general case:
def if_iter(a, b, testfunc):
    if testfunc(a, b):
        yield a

in order to do then

for tmp in cmp_iter(my_func(x), some_value):
    frobnicate(tmp)
    return tmp

This for loop does not run if the condition is not fulfilled and runs exactly once if the condition is fulfilled.

It is quite unusual, however, and might confuse potential readers of your code, so either refrain from doing so or do a very well documentation.

2
  • I don't need the loop, but maybe you can make a user defined comparison cmp function manipulate the symbol table of calling statement to set a it variable.
    – mmj
    Dec 4, 2012 at 11:34
  • @mmy It would probably much more complicated than this solution. It does all you want...
    – glglgl
    Dec 4, 2012 at 12:40
-1

I found a neat solution (better ones are welcomed) using a decorator which saves the last value returned by the decorated function in the last attribute. My construct becomes:

if my_func(x) == some_value:
    # do anything with the value returned by my_func, saved in my_func.last
    # such as
    print my_func.last
    return my_func.last

Concise and clear. The function is evaluated only once and you don't need to introduce an annoying temporary variable.

Of course you must remember to decorate the functions which you want to 'enable' the last attribute for, using (assumed that the decorator name is save_last):

@save_last
def my_func(...):
    # function definition

The decorator is defined as:

# last value returned by decorated function is accessible as 'last' attribute
def save_last(f):
    def w(*args, **kwargs): # w is the 'wrapper' function
        w.last=f(*args, **kwargs)
        return w.last
    return w
4
  • 1
    Hello. What is your aim ? I find this solution astute but it is a lot of machinery just to avoid to create a new name tmp. Is this name susceptible to be created only once, or is there a kind of cyclic algorithm that is susceptible to repeatedly testing if it must create this name ?
    – eyquem
    Feb 5, 2014 at 2:18
  • 1
    If your aim is to avoid a name, I find that having to write several lines to define a decorator and to apply it to the function isn't good way to limit the names employed .... If your aim is to avoid the number of objects created during the execution, it is no more an interesting solution.... I'm perplexed by your "desire".
    – eyquem
    Feb 5, 2014 at 2:22
  • Possibility of a solution depends also of the code block of the function my_func. I mean, what are the names used in the code block of the function
    – eyquem
    Feb 5, 2014 at 2:23
  • Dear anonymous downvoter, please explain me why this answer is not useful, since I'm using it repeatedly in my code.
    – mmj
    Apr 3, 2015 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.