Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python Functions, Param Type Checking + Strict Value Checking

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>>> 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!

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading