Skip to content
Advertisement

How to make a custom annotation that the type checker will recognize as str?

I want to use the argument annotation to define a parser for the argument.

Here is an example:

def parser(arg: str) -> str:
    return do_something(arg)

def foo(a: parser):
    # get arg's annotation and parse it
    return get_annotation(foo, "a")(a)

The problem is when I call the function with an argument of type str the type checker warns me that it’s not of type parser.

foo("hello")

My question: How can I get the best of both worlds and use the annotation feature to get parser where the type checker will get str? (Preferably without using Union)

Maybe if something like this could work:

def foo(a: parser[str]):
    # get arg's annotation and parse it
    return get_annotation(foo, "a")(a)

foo("hello") # this compiles without any warnings

Sort of like Optional or Union return one object but the type checker analyzes them as different objects.

Advertisement

Answer

Python 3.9 added the Annotated type, so you can do this:

def foo(a: Annotated[str, parser]):
    # a is of type str, but has parser as metadata
    pass
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement