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

How to test __annotations__ member has same type as generic class parameter?

  • Thread starter Thread starter Ouroboros
  • Start date Start date
O

Ouroboros

Guest
I want to be able to select only annotated members that have the same type as the parameter of generic in this base class:

Code:
from typing import Generic, TypeVar


T = TypeVar("T")

class MarkFinder(Generic[T]):
    def __init_subclass__(cls, **kwargs):
        cls.marked = tuple(
            name for name, annotated_type in cls.__annotations__.items() 
            if some_condition(annotated_type)
        )

So that if I inherit:

Code:
T2 = TypeVar("T2")

class Inheritor(MarkFinder[T2]):
    a: T2
    b: int
    c: T2

Then Inheritor.marked should just be ('a', 'c').

I have tried to replace some_condition(annotated_type) with:

cls.__parameters__[0] is annotated_type or cls.__parameters__[0] == annotated_type

but even though they have the same names, the types are not equal.

What is the correct condition? Or is this impossible?
<p>I want to be able to select only annotated members that have the same type as the parameter of generic in this base class:</p>
<pre class="lang-py prettyprint-override"><code>from typing import Generic, TypeVar


T = TypeVar("T")

class MarkFinder(Generic[T]):
def __init_subclass__(cls, **kwargs):
cls.marked = tuple(
name for name, annotated_type in cls.__annotations__.items()
if some_condition(annotated_type)
)
</code></pre>
<p>So that if I inherit:</p>
<pre class="lang-py prettyprint-override"><code>T2 = TypeVar("T2")

class Inheritor(MarkFinder[T2]):
a: T2
b: int
c: T2
</code></pre>
<p>Then <code>Inheritor.marked</code> should just be <code>('a', 'c')</code>.</p>
<p>I have tried to replace <code>some_condition(annotated_type)</code> with:</p>
<p><code>cls.__parameters__[0] is annotated_type</code> or <code>cls.__parameters__[0] == annotated_type</code></p>
<p>but even though they have the same names, the types are not equal.</p>
<p>What is the correct condition? Or is this impossible?</p>
 

Latest posts

Z
Replies
0
Views
1
zuegelwagen
Z
Top