I have a somewhat tricky python typing question. I have a function (generator) that iterates over a list of objects, and then over a particular attribute of each of these objects like this:
T = TypeVar('T')
S = TypeVar('S')
def iter_attribute(outer: Iterable[T], attribute: str) -> Iterable[S]:
for item in outer:
yield from getattr(item, attribute)
How would I properly convey the fact that T
should have an iterable attribute called attribute
that yields S
objects? By the way, mypy is totally happy with this and doesn’t catch this:
class A:
a: str
def __init__(self, a: str):
self.a = a
a: str
for a in iter_attribute([A('a'), A('b'), A('c')], 'b'):
print(a)
How would I correctly type this?