Search code examples
pythonpython-typingpyrightpython-3.12

Python typehints: Union of type complex types not working as expected with user defined classes


I was trying to create a type alias that matches Callables with different numbers of arguments like this:

from typing import Callable

class C:
    # no __add__ method, so all statements below should give an error
    pass

type F[T1, T2] = Callable[[T1], T2] | Callable[[T1, T1], T2]

b: Callable[[C], C] = lambda a, b: a + b # error
a: Callable[[C, C], C] = lambda a, b: a + b # error


# but:
c: F[C, C] = lambda a, b: a + b # no error

But as illustrated it doesnt work if I instantiate it with a class C, as it should also give an error for c. It does work as expected with built-in types like that don't support +:

d: F[set, set] = lambda a, b: a + b # error

I am using the latest version of pyright (1.1.360)

Is this

  • a limitation of pyright?
  • or a bug of pyright?
  • or do need to do sth to make this work with classes?

Solution

  • This is a bug. The fix will be available in 1.1.361.