Late answer but hope it can help someone else!
from enum import Enum
from typing import Type, TypeVar, Union
class ProtocolType(Enum):
HTTP = "http"
HTTPS = "https"
T = TypeVar("T")
def validate_enum(value: T, enum_type: Type[Enum]) -> T:
if not any(value == item.value for item in enum_type):
raise ValueError(f"Invalid value: {value}")
return value
def my_request(protocol_type: Union[ProtocolType, str], url: str):
protocol_type = validate_enum(protocol_type, ProtocolType)
print(f"Making a {protocol_type} request to {url}")
# valid calls
my_request("http", "example.com")
my_request("https", "example.com")
# invalid call
my_request("ftp", "example.com")
In this example, we've defined a validate_enum function that takes an enum value and type as arguments. The function checks if the given value matches one of the valid values in the enum. If so, it returns the value, otherwise it throws ValueError.
Then in my_request function we use this validate_enum function to validate the value of protocol_type as ProtocolType enum. This ensures that the value passed to the function is either a member of the enum or a valid string.
This allows you to have validation at the function definition level.