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 declare a method on a Python union type alias?

  • Thread starter Thread starter Nathaniel Ford
  • Start date Start date
N

Nathaniel Ford

Guest
Suppose I have two classes, A and B:

Code:
class A:
  def f(self) -> bool:
    ...

class B:
  def f(self) -> bool:
    ...

And later I type alias these:

Code:
from typing import Union
FClass: TypeAlias = Union[A, B]

So that in another place I can have a function:

Code:
def g() -> FClass:
  ...  # Returns an object that is either A or B.


n = g()
n.f()  # This complains!

The call to f() here looks bad to checkers because f() is not declared on FClass even though it's declared on all possible types. Is there a way to declare the method will always exist on classes with that alias (something akin to a Java interface)? Or is there a better way to go about this? The specific complaint:

Code:
'A | B' has no attribute 'f'

Note that A and B are out of my control, as is the internals of g(). The practical use case is a multi-track library (i.e. 'alpha', 'beta', 'general audience') that have different generated internal objects, but that share an API.
<p>Suppose I have two classes, <code>A</code> and <code>B</code>:</p>
<pre><code>class A:
def f(self) -> bool:
...

class B:
def f(self) -> bool:
...
</code></pre>
<p>And later I type alias these:</p>
<pre><code>from typing import Union
FClass: TypeAlias = Union[A, B]
</code></pre>
<p>So that in another place I can have a function:</p>
<pre><code>def g() -> FClass:
... # Returns an object that is either A or B.


n = g()
n.f() # This complains!
</code></pre>
<p>The call to <code>f()</code> here looks bad to checkers because <code>f()</code> is not declared on <code>FClass</code> even though it's declared on all possible types. Is there a way to declare the method will always exist on classes with that alias (something akin to a Java interface)? Or is there a better way to go about this? The specific complaint:</p>
<pre><code>'A | B' has no attribute 'f'
</code></pre>
<p>Note that <code>A</code> and <code>B</code> are out of my control, as is the internals of <code>g()</code>. The practical use case is a multi-track library (i.e. 'alpha', 'beta', 'general audience') that have different generated internal objects, but that share an API.</p>
 
Top