How to collate the arguments features to create a set of values from an Enum?
For a more general solution, see below; for a solution for Fields
specifically and which doesn't need *args
(or *members
as the case may be...) check out Tomer Shetah's answer.
General Solution
To make Query
more generalized and usable with other Enums, I would specify which Field
members you wanted:
class Query:
#
def __init__(self, *members):
self.query_fields = set()
for member in members:
self.query_fields.update(member.value)
and in use:
>>> x = Query()
>>> x.query_fields
set()
>>> y = Query(Fields.a, Fields.c)
>>> y.query_fields
{'world', 'the', 'hello', 'what'}
If your defaults are common, you can put them in another variable and use that:
>>> fields_default = Fields.a, Fields.b
>>> z = Query(*fields_default)
>>> z.query_fields
{'foo', 'bar', 'world', 'hello', 'sheep'}
You can iterate over Fields to get all the elements, and then use that .name or .value to get the respective attribute.
from enum import Enum
class Fields(Enum):
a = ["hello", "world"]
b = ["foo", "bar", "sheep"]
c = ["what", "the"]
d = ["vrai", "ment", "cest", "vrai"]
e = ["foofoo"]
class Query:
defaults = [True, True, False, False, False]
def __init__(self, **kwargs):
self.query_fields = set()
for attr, default in zip(Fields, self.defaults):
if attr.name in kwargs:
if kwargs[attr.name]:
self.query_fields.update(attr.value)
elif default:
self.query_fields.update(attr.value)
x = Query()
print(x.query_fields)
x = Query(a=False, e=True)
print(x.query_fields)
Note that the number of elements in fields and their order is hardcoded in Query.defaults, but I dont think it makes sense for that not to be the case.