Skip to content

Commit

Permalink
tests/docs(query_list): Document object lookups
Browse files Browse the repository at this point in the history
  • Loading branch information
tony committed Sep 18, 2022
1 parent 9989639 commit 432f1e2
Showing 1 changed file with 99 additions and 0 deletions.
99 changes: 99 additions & 0 deletions src/libvcs/_internal/query_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ def parse_lookup(obj: Mapping[str, Any], path: str, lookup: str) -> Optional[Any
>>> parse_lookup({ "food": "red apple" }, "food__istartswith", "__istartswith")
'red apple'
It can also look up objects:
>>> from dataclasses import dataclass
>>> @dataclass()
... class Inventory:
... food: str
>>> item = Inventory(food="red apple")
>>> item
Inventory(food='red apple')
>>> parse_lookup(item, "food__istartswith", "__istartswith")
'red apple'
"""
try:
if isinstance(path, str) and isinstance(lookup, str) and path.endswith(lookup):
Expand Down Expand Up @@ -262,6 +278,89 @@ class QueryList(list[T]):
'Elmhurst'
>>> query.filter(foods__fruit__in="orange")[0]['city']
'Tampa'
Examples of object lookups:
>>> from typing import Any
>>> from dataclasses import dataclass, field
>>> @dataclass()
... class Restaurant:
... place: str
... city: str
... state: str
... foods: dict[str, Any]
>>> restaurant = Restaurant(
... place="Largo",
... city="Tampa",
... state="Florida",
... foods={
... "fruit": ["banana", "orange"], "breakfast": "cereal"
... }
... )
>>> restaurant
Restaurant(place='Largo',
city='Tampa',
state='Florida',
foods={'fruit': ['banana', 'orange'], 'breakfast': 'cereal'})
>>> query = QueryList([restaurant])
>>> query.filter(foods__fruit__in="banana")
[Restaurant(place='Largo',
city='Tampa',
state='Florida',
foods={'fruit': ['banana', 'orange'], 'breakfast': 'cereal'})]
>>> query.filter(foods__fruit__in="banana")[0].city
'Tampa'
Example of deeper object lookups:
>>> from typing import Optional
>>> from dataclasses import dataclass, field
>>> @dataclass()
... class Menu:
... fruit: list[str] = field(default_factory=list)
... breakfast: Optional[str] = None
>>> @dataclass()
... class Restaurant:
... place: str
... city: str
... state: str
... menu: Menu = field(default_factory=Menu)
>>> restaurant = Restaurant(
... place="Largo",
... city="Tampa",
... state="Florida",
... menu=Menu(
... fruit=["banana", "orange"], breakfast="cereal"
... )
... )
>>> restaurant
Restaurant(place='Largo',
city='Tampa',
state='Florida',
menu=Menu(fruit=['banana', 'orange'], breakfast='cereal'))
>>> query = QueryList([restaurant])
>>> query.filter(menu__fruit__in="banana")
[Restaurant(place='Largo',
city='Tampa',
state='Florida',
menu=Menu(fruit=['banana', 'orange'], breakfast='cereal'))]
>>> query.filter(menu__fruit__in="banana")[0].city
'Tampa'
"""

data: Sequence[T]
Expand Down

0 comments on commit 432f1e2

Please sign in to comment.