OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Python typing for nested iterator on list of objects with iterable property

  • Thread starter Thread starter Ingo
  • Start date Start date
I

Ingo

Guest
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:

Code:
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:

Code:
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?
<p>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:</p>
<pre class="lang-py prettyprint-override"><code>T = TypeVar('T')
S = TypeVar('S')

def iter_attribute(outer: Iterable[T], attribute: str) -> Iterable:
for item in outer:
yield from getattr(item, attribute)
</code></pre>
<p>How would I properly convey the fact that <code>T</code> should have an iterable attribute called <code>attribute</code> that yields <code>S</code> objects? By the way, mypy is totally happy with this and doesn't catch this:</p>
<pre class="lang-py prettyprint-override"><code>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)
</code></pre>
<p>How would I correctly type this?</p>
 
Top