type hint returns NameError: name ‘datetime’ not defined

You need to import datetime, or use a string (remember, it is just an hint). >>> def f(x: datetime): … pass … Traceback (most recent call last): File “<stdin>”, line 1, in <module> NameError: name ‘datetime’ is not defined >>> def f(x: ‘datetime’): … pass … >>> >>> from datetime import datetime >>> def f(x: … Read more

Using the class as a type hint for arguments in its methods [duplicate]

Because when it encounters Translate (while compiling the class body), Vector2 hasn’t been defined yet (it is currently compiling, name binding hasn’t been performed); Python naturally complains. Since this is such a common scenario (type-hinting a class in the body of that class), you should use a forward reference to it by enclosing it in … Read more

How do I correctly add type-hints to Mixin classes?

For reference, mypy recommends to implement mixins through a Protocol (documentation here). It works with mypy >= 750. from typing import Protocol class HasValueProtocol(Protocol): @property def value(self) -> int: … class MultiplicationMixin: def multiply(self: HasValueProtocol, m: int) -> int: return self.value * m class AdditionMixin: def add(self: HasValueProtocol, b: int) -> int: return self.value + … Read more

typing: Dynamically Create Literal Alias from List of Valid Values

Go the other way around, and build VALID_ARGUMENTS from Argument: Argument = typing.Literal[‘foo’, ‘bar’] VALID_ARGUMENTS: typing.Tuple[Argument, …] = typing.get_args(Argument) It’s possible at runtime to build Argument from VALID_ARGUMENTS, but doing so is incompatible with static analysis, which is the primary use case of type annotations. Building VALID_ARGUMENTS from Argument is the way to go. I’ve … Read more

Defining a recursive type hint in Python?

You can specify recursive types in the typing language by using type aliases and forward reference strings, Garthoks = Union[Garthok, Iterable[‘Garthoks’]] Note that recursive types are not yet supported by mypy. But it will likely be added eventually. Update 2020/9/14: Microsoft announces support for recursive types in Pyright/Pylance. Some types of forward references are handled … Read more

Specify length of Sequence or List with Python typing module

You can’t. A list is a mutable, variable length structure. If you need a fixed-length structure, use a tuple instead: Tuple[float, float, float, float, float, float, float, float, float, float] Or better still, use a named tuple, which has both indices and named attributes: class BunchOfFloats(NamedTuple): foo: float bar: float baz: float spam: float ham: … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)