-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
75 lines (65 loc) · 1.55 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#!/usr/bin/env python3
"""Generic utilities for github org client.
"""
import requests
from functools import wraps
from typing import (
Mapping,
Sequence,
Any,
Dict,
Callable,
)
__all__ = [
"access_nested_map",
"get_json",
"memoize",
]
def access_nested_map(nested_map: Mapping, path: Sequence) -> Any:
"""Access nested map with key path.
Parameters
----------
nested_map: Mapping
A nested map
path: Sequence
a sequence of key representing a path to the value
Example
-------
>>> nested_map = {"a": {"b": {"c": 1}}}
>>> access_nested_map(nested_map, ["a", "b", "c"])
1
"""
for key in path:
if not isinstance(nested_map, Mapping):
raise KeyError(key)
nested_map = nested_map[key]
return nested_map
def get_json(url: str) -> Dict:
"""Get JSON from remote URL.
"""
response = requests.get(url)
return response.json()
def memoize(fn: Callable) -> Callable:
"""Decorator to memoize a method.
Example
-------
class MyClass:
@memoize
def a_method(self):
print("a_method called")
return 42
>>> my_object = MyClass()
>>> my_object.a_method
a_method called
42
>>> my_object.a_method
42
"""
attr_name = "_{}".format(fn.__name__)
@wraps(fn)
def memoized(self):
""""memoized wraps"""
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)
return property(memoized)