Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python sum(generator): calling an external function

take the code:

SUM = sum(x() for x in xs)

I am writing some code that is in need of calling another function before each x() such that x() will compute the right value

is the only way to do this like so?

for x in xs: x.pre()

SUM = sum(x() for x in xs)

or

SUM = 0
for x in xs:
    x.pre()
    SUM += x()

incorporating x.pre into x is obviously possible but would make the real code exceptionally ugly and hard to read. is there some way of using generator expressions I am unaware of that would allow what I am trying to achieve?

eg:

SUM = sum(x(), x.pre() for x in xs) 

thats obviously just an non-summable tuple generator

like image 601
user2255757 Avatar asked Nov 26 '25 08:11

user2255757


1 Answers

I would simply use the for-loop you already presented.

There are ways to do what you want in other ways. For example you could use functools.reduce with a customized function here instead of sum :

def pre_then_add(accumulated, new_one):
    new_one.pre()  # do some stuff so we get the right value
    return accumulated + new_one() # add the value to the accumulated sum

and then it's just a matter of calling reduce:

import functools

functools.reduce(pre_then_add, xs, 0)

Note that this requires to give a "base value" otherwise the function is too simple but also that reduce with a customized function is not necessarily the most efficient or elegant way.

As pointed in the comments (thanks to @SteveJessop) another possibility using sum would be:

def pre_then_call(x): 
    x.pre(); 
    return x()

sum(pre_then_call(x) for x in xs)

But just to repeat it: I would use the explicit loop. Those are far easier to understand in terms of what you are doing and why.

like image 55
MSeifert Avatar answered Nov 28 '25 21:11

MSeifert