Skip to content

add a note on extracting multiline processing in comprehensions - #148

Open
graingert wants to merge 2 commits into
quantifiedcode:masterfrom
graingert:patch-2
Open

add a note on extracting multiline processing in comprehensions#148
graingert wants to merge 2 commits into
quantifiedcode:masterfrom
graingert:patch-2

Conversation

@graingert

Copy link
Copy Markdown
Contributor

follow up to #135

def cond(v): ...

[process(x) for x in items if cond(v)] # preferable to map(process, filter(cond, items))

@graingertgraingertFeb 28, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how about also a note on how to combine cond and process?

Sometimes a condition or process may repeat computation unnecessarily, in those cases extract a function that returns an iterable with the result or an empty iterable:
.. code:: python hams = [x["ham"] for x in items if"ham"in x] # duplicate key lookup.. code:: pythondefprocess(x):try:return (x["ham"],)exceptKeyError:return () hams = [ham for x in items for ham in process(x)]

@graingertgraingertFeb 28, 2020

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's also often possible to inline this empty iterable into the comprehension
.. code:: python hams = [x["ham"] for x in items if x.get("ham") isnotNone] # duplicated key lookup.. code:: python hams = [ hamfor x in itemsfor ham in (x.get("ham"),)if ham isnotNone ]and alternative in python 3.8+ is
.. code:: python hams = [ hamfor x in itemsif (ham := x.get("ham")) isnotNone ]

Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant

@graingert