Why does this Python function not throw an error when Enum value is not matched?

Viewed 222

If I have a python function with the following color arg defined:

def search(
    self,
    color: ColorEnum = None
) -> Result:

And the ColorEnum looks like this:

class ColorEnum(str, Enum):
    Red = "red",
    Green = "green",
    Blue = "blue"

Why does Python not throw an error when I do the following:

search(color="black")

Is the Enum value merely used at compile time? It seems not to have any effect at run time and the function will work

1 Answers

Function annotations are just "notes" you can attach to function parameters and the return type. They have no effect at runtime, though you can access them.

>>> def foo(x: int) -> str: pass
...
>>> foo.__annotations__
{'x': <class 'int'>, 'return': <class 'str'>}

If you chose to, you could use them to implement your own type-checking code:

def foo(x: int) -> str:
    if not isinstance(x, foo.__annotations__('x')):
        raise ValueError("x is not the right type")
    rv = str(x)
    if not isinstance(rv, foo.__annotations__('return')):
        raise ValueError("wrong return type")
    return rv

This is, of course, easily defeated, and is as likely to introduce bugs as to catch them.

Type hints provide documentation ("You should pass an int as an argument, and you should return a str value.") and a means for a static typechecker to catch obvious errors. Given the clean definition

def foo(x: int) -> str:
    return str(x)

a tool like mypy can flag code like the following as an error without having to execute the code:

foo("nine")  # "nine" does not have type int
3 + foo(5)   # foo returns a str, but you can't add int and str values
Related