-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Making a store out of a (data fetching) function list.
Relevant to #54.
- Loading branch information
twhalen
committed
Apr 7, 2020
1 parent
81199a1
commit 561f65b
Showing
1 changed file
with
42 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
# from py2store.util import lazyprop, num_of_args | ||
from py2store.base import KvReader | ||
|
||
|
||
class FuncReader(KvReader): | ||
"""Reader that seeds itself from a data fetching function list | ||
Uses the function list names as the keys, and their returned value as the values. | ||
For example: You have a list of urls that contain the data you want to have access to. | ||
You can write functions that bare the names you want to give to each dataset, and have the function | ||
fetch the data from the url, extract the data from the response and possibly prepare it | ||
(we advise minimally, since you can always transform from the raw source, but the opposite can be impossible). | ||
>>> def foo(): | ||
... return 'bar' | ||
>>> def pi(): | ||
... return 3.14159 | ||
>>> s = FuncReader([foo, pi]) | ||
>>> list(s) | ||
['foo', 'pi'] | ||
>>> s['foo'] | ||
'bar' | ||
>>> s['pi'] | ||
3.14159 | ||
""" | ||
|
||
def __init__(self, funcs): | ||
# TODO: assert no free arguments (arguments are allowed but must all have defaults) | ||
self.funcs = funcs | ||
self._func_of_name = {func.__name__: func for func in funcs} | ||
|
||
def __contains__(self, k): | ||
return k in self._func_of_name | ||
|
||
def __iter__(self): | ||
yield from self._func_of_name | ||
|
||
def __len__(self): | ||
return len(self._func_of_name) | ||
|
||
def __getitem__(self, k): | ||
return self._func_of_name[k]() # call the func |