Skip to content
Advertisement

Tag: mypy

Python annotate type as regex pattern

I have a dictionary annotation The value of time: will always be formatted like 2022-01-01 00:00:00, or “%Y-%m-%d %H:%M:%S”. I’d like a way to express this in the type annotation Something like WIth the goal of IDE hinting through VSCode Intellisense and Pylance. Are regex-defined type annotations supported? Answer Leaving out philosophical discussions about what should or should not be

mypy does not detect errors when wrongly using a function imported from an external package

I’ve run a simple experiment where I’ve created a very simple python package containing the following files: In the folder my_package: An empty __init__.py In the root folder, a setup.py file: After building the package using python ./setup.py bdist_wheel I’ve copied the .whl file to another python project, ran pip install ExamplePackage-0.1.0-py3-none-any.whl and created the following file main.py: My mypy.ini

MyPy complains about datetime difference

MyPy complains about the line of code where bar is assigned the difference of two datetimes. The type of foo is datetime.timedelta. The error message from MyPy is “int not callable”. What am I missing? Answer This turned out to be a known issue. For details, see the following: https://github.com/python/mypy/issues/11613

Declare type annotation for optional dependency

Lets say I want to declare an input type originating from an optional dependency of my library. I have the option to set it as a string, at least to make Python happy (e.g. not complain about the missing name). But then Mypy will of course not know what to do about this missing type. Is there any solution, without

Type annotation for partial functions

we have multiple partial-like functions with same type annotation with args and kwargs like: can I somehow create a template for functions apple, orange, banana and assign it to them? I thought about Protocol with __call__ definition, but it is unclear how to assign it to functions Answer Rather than a function, you can use functools.partial: Another possibility would be

How to annotate that a function produces a dataclass?

Say you want to wrap the dataclass decorator like so: How should my_dataclass and/or something_else be annotated to indicate that the return type is a dataclass? See the following example on how the builtin @dataclass works but a custom @my_dataclass does not: Answer There is no feasible way to do this prior to PEP 681. A dataclass does not describe

Advertisement