mypy “is not valid as a type” for types constructed with `type()`

How about this, as a workaround? from typing import Optional, TYPE_CHECKING if TYPE_CHECKING: class Foo: pass else: Foo = type(‘Foo’, (), {}) Bar = Optional[Foo] typing.TYPE_CHECKING is a constant that will always be True at compile-time, and will always be False at runtime. In this way, we can keep MyPy happy by only telling it … Read more

A way to subclass NamedTuple for purposes of typechecking

The way named tuples are constructed make inheritance from typing.NamedTuple classes as yet not possible. You’d have to write your own metaclass to extend the typing.NamedTupleMeta class to make subclassing work, and even then the class generated by collections.namedtuple() is just not built to extend. Instead, you want to use the new dataclasses module to … Read more

Why does PyCharm not accept my type hint for an empty list?

Looking at PEP 484, specifically the section on type comments (the precursor to variable annotations) this does indeed seem like a bug with PyCharm’s checker. Quoting from the PEP: In non-stub code, there is a similar special case: from typing import IO stream = None # type: IO[str] Type checkers should not complain about this … Read more

How to type hint a Callable of a function with default arguments?

Define this: class Foo(Protocol): def __call__(self, x: int = …, /) -> float: … then type hint foo as Foo instead of Callable[[int], float]. Callback protocols allow you to: define flexible callback types that are hard (or even impossible) to express using the Callable[…] syntax and optional arguments are one of those impossible things to … Read more

Type Hints Convention for Instance Variables Python

I would recommend using the first version, where you assign types to your __init__ method’s parameters, for most circumstances. That particular method has the least amount of redundancy while still allowing type checkers to verify that you’re calling that __init__ method correctly elsewhere in your code. I would recommend using either the second or third … Read more

Python class members type hinting

PyCharm’s suggest is right. In fact, I think the following code is better: class DataAnalyzer: train_data: pd.DataFrame test_data: pd.DataFrame def __init__(self, train_data, test_data): self.train_data = train_data self.test_data = test_data def analyze(self): pass Explain: Annotate a member does not make it static. We should not annotate arguments in the __init__ function again. -> None after __init__ … Read more

Generic[T] base class – how to get type of T from within instance?

There is no supported API for this. Under limited circumstances, if you’re willing to mess around with undocumented implementation details, you can sometimes do it, but it’s not reliable at all. First, mypy doesn’t require you to provide type arguments when assigning to a generically-typed variable. You can do things like x: Test[int] = Test() … Read more

How to use python typing.Annotated?

Annotated in python allows devs to declare type of a reference and and also to provide additional information related to it. name = Annotated[str, “first letter is capital”] This tells that name is of type str and that name[0] is a capital letter. On its own Annotated does not do anything other than assigning extra … Read more

How do I get Pylance to ignore the possibility of None?

There are many ways of forcing a type-checker to accept this. Use assert: from typing import Union def do_something(var: Union[T, None]): assert var is not None var.foo() Raise some other exception: from typing import Union def do_something(var: Union[T, None]): if var is None: raise RuntimeError(“NO”) var.foo() Use an if statement: from typing import Union def … Read more