Skip to content

Instantly share code, notes, and snippets.

@jhbuhrman
Created October 10, 2023 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhbuhrman/d2a00d0cfa852f80fdf40f961c5bdeb9 to your computer and use it in GitHub Desktop.
Save jhbuhrman/d2a00d0cfa852f80fdf40f961c5bdeb9 to your computer and use it in GitHub Desktop.
A perhaps pythonic application of `functools.reduce()`
import enum, functools, operator
from typing import Self
class Color(enum.IntFlag):
RED = enum.auto()
GREEN = enum.auto()
BLUE = enum.auto()
@classmethod
def from_string_pythonic(cls, string: str) -> Self:
colors = (cls[s] for s in string.split("|") if s)
return functools.reduce(operator.or_, colors, cls(0))
@classmethod
def from_string_less_pythonic(cls, string: str) -> Self:
result = cls(0)
if string:
for s in string.split("|"):
result |= cls[s]
return result
Color.from_string_pythonic("RED|BLUE")
# <Color.RED|BLUE: 5>
Color.from_string_less_pythonic("GREEN|BLUE")
# <Color.GREEN|BLUE: 6>
Color.from_string_pythonic("")
# <Color: 0>
Color.from_string_less_pythonic("")
# <Color: 0>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment