Performing a simple conversion on an iterable in Python is idiomatically accomplished with a list comprehension:
y = [f(arg) for arg in args]
where f
is a simple operator or a functional map
if f
is a named function:
y = map(f, args)
Guido maintains list listings over a map(lambda x:..., args)
and does list an understanding of using map
or filter
.
However, I do not understand how I can approach the problems that:
- change every item in iterable,
- non-trivial way
- using the discrete part of the logic (may be a function),
- which is not useful anywhere else
What is the most idiomatic way to solve this problem? Some things that I saw and tried in the Python projects I worked on:
Harbinger and cycle
The obvious way is to preliminarily state the conclusion and the loop:
def transform(...): ... y = [] for arg in args: first_statement second_statement ... y.append(statement)
Comments:
- (pro) easy to follow logic
- (con) logic is unlimited (abstraction leak)
- (con) logic is not explicit (how do you know its map without checking how all the branches in the loop work?)
- (con) overly predefines the variable in an irreplaceable way (
y
MUST be the same length as args
)
Nested function
Another option is to encapsulate the logic in a nested function, and then call it using a map or list definition:
def transform(...): ... def anonymous(arg): first_statement second_statement ... return statement y = map(anonymous, args)
Comments:
- (Pro) Encapsulates Logic
- (Pro) Access to the external area
- (Pro) It is not possible to change the external area (obviously there are no side effects)
- (Con) An internal function is redefined each time it is called.
- (Con) An internal function does not have a real name (must be anonymous in the scope of the map)
External function
Moving an internal function to an external range solves some of these problems, but introduces more:
def _anonymous(arg): first_statement second_statement ... return statement def transform(...): ... y = map(_anonymous, args)
Comments:
- (Pro): function compiles once during parsing
- (Con): the function is too far from the place of the call for a small part of the logic (causes an unnecessary context switch for the programmer)
- (Con): The function does not have access to the external area. Any requirements must be passed (preventing the use of
map
) or partial
ized
Summary
I am in conflict. How do you solve problems when you need to make a non-trivial discharge card?
source share