Код: Выделить всё
from typing import Literal
def func1(x: int):
"""Perform some work on integers."""
if not isinstance(x, int):
raise ValueError("x should be an integer.")
# Do some stuff.
def func2(x: float):
"""Perform some work on floats."""
if not isinstance(x, float):
raise ValueError("x should be a float.")
# Do some stuff.
def my_function(x: int | float, method: Literal[1, 2]):
"""Perform some work using one of two methods."""
match method:
case 1:
result = func1(x)
case 2:
result = func2(x)
case _:
raise ValueError(f"Invalid method: {method}.")
# Do some more work on result.
return result
EDIT: я должен отметить что я не хочу просто полагаться на тип x внутри my_function при выборе между функциями, поскольку пользователям было бы очень легко спутать целое число и число с плавающей запятой (например, опустив .0 в версии 1.0).
Подробнее здесь: https://stackoverflow.com/questions/774 ... -functions