Skip to content

Instantly share code, notes, and snippets.

@leshy
Last active October 5, 2017 19:39
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 leshy/c3c60a0e25732d040b9be0966376361e to your computer and use it in GitHub Desktop.
Save leshy/c3c60a0e25732d040b9be0966376361e to your computer and use it in GitHub Desktop.
# class dict does internally what next example does explicitly (builds a dict of { cls.__name__ : cls }
return f.map_keys(
arg(last, call('lower')), # equivalent to next example lambda
f.class_dict(
common.service.RestartableService.__subclasses__(),
common.service.Service.__subclasses__()
)).get(service_name.lower())
# list comprehension, but utilizing map_keys
# map keys goes through an iterable and generates a dict
# maybe my favorite one, but inefficient as it builds intermediate list and intermediate dict
return map_keys(
lambda v, k: v.__name__.lower(),
[
*common.service.RestartableService.__subclasses__(),
*common.service.Service.__subclasses__()
]
).get(service_name.lower())
# replaces map_keys with dict comprehension
return {
cls.__name__.lower(): cls
for cls in [
*common.service.RestartableService.__subclasses__(),
*common.service.Service.__subclasses__()
]
}.get(service_name.lower())
# removed dict comprehension with on the fly matching and return (more efficient)
service_name = service_name.lower()
for cls in [*common.service.RestartableService.__subclasses__(),
*common.service.Service.__subclasses__()]:
if cls.__name__.lower() == service_name: return cls
# even faster, not constructing intermediate list, but chaining iterables (itertools.chain)
# --- went with this, this is pure python ---
service_name = service_name.lower()
for cls in chain(
common.service.RestartableService.__subclasses__(),
common.service.Service.__subclasses__()):
if cls.__name__.lower() == service_name: return cls
# fiterate is like chain() but will call functions encountered when neccessary during iteration
# (we save on calls if we match early)
service_name = service_name.lower()
for cls in f.fiterate(
common.service.RestartableService.__subclasses__,
common.service.Service.__subclasses__):
if cls.__name__.lower() == service_name: return cls
# most efficient to write, no need to add __subclass__ to each element,
# a bit harder to read but worth it for larger lists
service_name = service_name.lower()
for cls in f.fiterate(
map(call('__subclasses__'),
(common.service.RestartableService,
common.service.Service))):
if cls.__name__.lower() == service_name: return cls
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment