How do I annotate a function that takes AnyStr with a str default value?

I wish to type-annotate a function that takes an AnyStr argument that defaults to a str and also returns an AnyStr of the same type. However, if I write this:

from typing import AnyStr

def func(s: AnyStr = ".") -> AnyStr:
    return s

then mypy fails with "Incompatible default for argument "s" (default has type "str", argument has type "bytes")".

I also tried splitting the code into a .py and .pyi file like so:

.py file:

def func(s = "."):
    return s

.pyi file:

from typing import AnyStr

def func(s: AnyStr = ...) -> AnyStr:
    ...

... but I must be invoking mypy wrong, because it fails to type-check the invocations of func; e.g., if I add func(42) to the .py file, mypy doesn't complain.

What is the correct way to annotate my function and get the code to be completely type-checked?



Read more here: https://stackoverflow.com/questions/66279051/how-do-i-annotate-a-function-that-takes-anystr-with-a-str-default-value

Content Attribution

This content was originally published by jwodder at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: