Python Functions, Param Type Checking + Strict Value Checking

Question:

I like to define parameter types when writing Python to give the reader an easy understanding of what should be passed into a function, and what the type of data is going to look like. For example,

def reverse_string(string_to_reverse: str) -> str:
   ...
   return reversed_string

I have a special case however, where the function I am making is not only of the type str, but also should always be passed one of two string values. Anything else SHOULD throw and exception and let the user know something messed up.

In code, this should look like,

>>> def some_func(test_string: str["test_string_1", "test_string_2"]) -> str:
...    return f"Valid string passed '{test_string}'"
...
>>> some_func("test_string_1") # ✔️
... "Valid string passed 'test_string_1'"
>>> some_func("test_string_2") # ✔️
... "Valid string passed 'test_string_2'"
>>> some_func("test_string_3") # ❌
... "EXCEPTION: SOME EXCEPTION MESSAGE THROWN HERE"

Is there a way to enforce this in Python, with or without libraries?

Suggestions are appreciated.

Thanks!

Asked By: Saif Ul Islam

||

Answers:

Python >= 3.8 supports Literal type, in your case it would be

from typing import Literal

def some_func(test_string: Literal["test_string_1", "test_string_2"]):
    ...

This, however, will only provide static type analysis and will not raise any run-time exceptions (as any other Python type annotations/ hints won’t). For these you will have to use assert or explicitly raise an exception.

Answered By: DeepSpace
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.