Sometimes, I just want to execute a function for a list of entries -- eg.:
for x in wowList:
installWow(x, 'installed by me')
Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:
map(lambda x: installWow(x, 'installed by me'), wowList)
But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.
(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)
You might try this:
That way, the return result is an empty list no matter what.
Or you could just drop the
and False
if you can forceinstallWow()
to always returnFalse
(or 0 orNone
or another expression that evaluates false).Someone needs to answer --
The more pythonic way here is to not worry about polluting the namespace, and using
__all__
to define the public variables.Then
How about this?
Every expression evaluates to something, so you always get a result, whichever way you do it. And any such returned object (just like your list) will get thrown away afterwards because there's no reference to it anymore.
To clarify: Very few things in python are statements that don't return anything. Even a function call like
still returns a value, even if it gets discarded right away. There is no such thing as Pascal's function / procedure distinction in python.
You could make your own "each" function:
Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't leak into the current scope.
first rewrite the for loop as a generator expression, which does not allocate any memory.
But this expression doesn't actually do anything without finding some way to consume it. So we can rewrite this to yield something determinate, rather than rely on the possibly
None
result ofinstallWow
.which creates a list, but returns only the constant 1. this can be consumed conveniently with
reduce
Which conveniently returns the number of items in wowList that were affected.