Picklist is a user-friendly list to pick element with conditions.
# normal way
[personforpersoninperson_listifperson.name=="John"][0]
# equivalent with picklistperson_list.pick(name="John") # easy!$ python -m pip install git+https://github.com/yoko72/picklist
With following data:
fromdataclassesimportdataclassfrompicklistimportPickList@dataclassclassPerson:
name: strage: intJohn=Person("John", 35)
Smith=Person("Smith", 22)
persons=PickList([John, Smith])Let's pick an element whose value of "name" attribute is "John".
persons.pick(name="John") # == John# Even .pick is omitted, it works same.The pick method accepts any keyword arguments(key=value), and returns the element which satisfies all element.key == value conditions.
It's almost equivalent to following ways.
# for loopJohn=Noneforpersoninpersons:
ifperson.name=="John":
John=personbreak# comprehensiontry:
John= [personforpersoninpersonsifperson.name=="John"][0]
exceptIndexError: # if list is empty:John=NoneComprehension way differs a little from pick method and for loop. It doesn't stop the process even after it finds the object.
Not only objects holding value as attr, but also dictlike object is available. Let's see the example of dict.
John_dict= {"name": "John", "age": 35}
Smith_dict= {"name": "Smith", "age": 22}
plist=PickList([John_dict, Smith_dict])
plist.pick(name="Smith") # is Smith_dictget_all() returns list of all elements satisfying the conditions as picklist.
persons=PickList([Person("Abigail", 35),
Person("John", 35),
Person("Smith", 22)])
persons_aged_35=persons.get_all(age=35) # == PickList([person for person in persons if person.age==35])If you want names of all persons,
names=persons.names# ["Abigail", "John", "Smith"]# persons.get_values("name") also works same.It's equivalent with:
names= [person.nameforpersoninpersons]Nothing has "names" attribute, but all elements have "name" attribute. If picklist is accessed with undefined attribute with "s" suffix, each element is checked if they have the attribute without "s" suffix. If they have, picklist returns the values of each element as PickList. If not, AttributeError is raised.
This usage comes from the usage of multiple form in English, but it purely checks if it ends with "s" or not. Therefore, incorrect english words are possible like picklist.informations, plist.womans and so on.
You can use get_values method if you don't like such usage, it works same.
Followings are equivalent.
plist.get_values("example")
plist.examplesYou can extract with complicated conditions by giving callable as positional argument. The callable must accept one argument, and the element is extracted only when bool(Callable(element)) is True.
example=persons.pick(
lambdaperson: person.name.startswith("A")
andperson.weight>45.0,
age=27, height=160)Picklist inherits from standard class. Each method or operator for the list is available.