Consolidate behavior by using filterfalse and always_iterable #3265
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
As I was searching through the code for a completely different purpose, I stumbled across this pattern, which I've seen many times before:
This common pattern is the reason I created always_iterable, as it allows looping over the items even if there's just one.
Using this technique, along with filterfalse, the code is more concise, less nested, and in my opinion, more directly conveys the intention. One slightly awkward aspect is that the for loop is abruptly terminated if it fails the isclass test, but that was the behavior before as well.
The main reservation I have about this change is that it adds a new dependency, and I'm unsure how important it is to avoid new dependencies. Given that more_itertools implements the recipes from itertools, I find that it tends to have broad appeal and would likely find beneficial use throughout the package (though I haven't surveyed it).
Thoughts?