DUE TO SPAM, SIGN-UP IS DISABLED. Goto Selfserve wiki signup and request an account.
Motivation
Currently, when writing Python UDFs, users who want to specify the result type and input types for the function must do so via the decorator, like this:
@udf( input_types=[DataTypes.BIGINT(), DataTypes.STRING()], result_type=DataTypes.STRING(), ) def repeat_string(count, text): return text * count
This feels both unpythonic and introduces friction with regards to input types, in that the list of input types must sequentially match the arguments in the function signature. If a new argument is added, it must also be added into the input types in the same position as it was added in the function signature.
For more complex UDFs, Python users might also leverage type hints on their function signatures so that they can have an extra layer of verification of UDF behaviour through a type checker like mypy or ty.
@udf( input_types=[DataTypes.BIGINT(), DataTypes.STRING()], result_type=DataTypes.STRING(), ) def repeat_string(count: int, text: str) -> str: return text * count
In the example above, notice that we are defining the types for the function in two places: both in the decorator (but as a DataType) and as type annotations on the arguments and function itself. What if we could unify these and infer the input and result DataType from the Python type annotations? So our resulting UDF would look like:
@udf() def repeat_string(count: int, text: str) -> str: return text * count
This would both remove the friction in defining the input/result types disconnected from the function signature and also encourage users to use type hinting more in the UDFs they write.
Public Interfaces
This FLIP adds a new enforce_input_types: bool = False parameter to the udf, udtf, udaf, and udtaf decorators, and changes the existing fallback behavior of input_types, result_type, result_types, and accumulator_type: when omitted and enforce_input_types = True, these are now resolved from the function's type hints instead of defaulting to WILDCARD input types or raising on a missing result type.
def udf(f: Union[Callable, ScalarFunction, AsyncScalarFunction, Type] = None, input_types: Union[List[DataType], DataType, str, List[str]] = None, result_type: Union[DataType, str] = None, deterministic: bool = None, name: str = None, func_type: str = "general", enforce_input_types: bool = False, ) -> Union[UserDefinedScalarFunctionWrapper, UserDefinedAsyncScalarFunctionWrapper, Callable]: ... .
Proposed Changes
Supported Types
There is already a type inference map within PyFlink that gets used when constructing a table from Python values via .from_values. These are:
| Python Type | DataType |
|---|---|
| bool | BOOLEAN |
| int | BIGINT |
| float | DOUBLE |
| decimal.Decimal | DECIMAL(38, 18) |
| str | VARCHAR(2147483647) |
| bytearray | VARBINARY(2147483647) |
| datetime.date | DATE |
However, as discussed in the nullability section below, these above types would also be emitted as NOT NULL.
In addition, we would propose adding the following types to the above type map used by .from_values:
| Python Type | DataType | Notes |
|---|---|---|
bytes | VARBINARY(2147483647) NOT NULL | Similar to bytearray. |
datetime.timedelta | INTERVAL(DAY(), SECOND()) NOT NULL | The conversion logic is already implemented in DayTimeIntervalType, only the lookup entry is missing |
Finally, we would add the following type inference machinery outside of the system currently used by .from_values, for use only in this annotation inference schema for UDFs:
| Python Annotation | Resolved DataType | Notes |
|---|---|---|
datetime.datetime | TIMESTAMP(6) NOT NULL | from_elements uses LocalZonedTimestampType() — annotations can't detect tz-awareness |
datetime.time | TIME(3) NOT NULL | |
Optional[T] / T | None | <resolved T> | |
list[T] | ARRAY(<resolved T>) NOT NULL | |
dict[K, V] | MAP(<resolved K>, <resolved V>) NOT NULL | |
| dataclass | ROW(...) NOT NULL | One field per dataclasses.fields(), in order |
Annotated[X, <DataType instance>] | the embedded DataType, as-is | This would be an escape hatch for users. See below. |
Iterator[T] / Iterable[T] / Generator[T,...] | unwrapped to T first | This mostly concerns UDTFs (generally) and UDTAFs (emit value specifically), as they are both generators. |
Tuple[T1, T2, ...] | list of resolved types, one per position | Only for UDTF's return annotation. |
Tuple[T1, T2, ...] | ROW<_1 T1, _2 T2, …> | Elsewhere outside of UDTF's return annotation. |
NamedTuple subclass | ROW(...) NOT NULL, one field per _fields entry | Already supported for values via _infer_schema; annotation-side equivalent |
TypedDict subclass | ROW(...) NOT NULL, one field per key; nullable per total=False/NotRequired[...] | Can't be inferred from a bare dict value |
Awaitable[T] / Coroutine[Any, Any, T] | Unwrapped to T first | For Async functions |
ListView[T] | DataTypes.LIST_VIEW(<resolved T>) | |
MapView[K, V] | DataTypes.MAP_VIEW(<resolved K>, <resolved V>) | |
Any | null | See "Any Type" section below |
Nullability
Flink's type system defaults to every boxed type being nullable unless explicitly marked with NOT NULL. Python, on the other hand, takes the opposite view. def f(x: int): signifies a function that should always get an integer, and never None. To do this in Python, you would want to annotate the argument with Optional[int] or int | None.
Because of this, in this inference schema, non-Optional type is inferred to be NOT NULL. The type signature of a function is a kind of contract over what data it expects and what data it outputs. We want to keep the function definition true to the actual shape of the function itself. If a function truly can handle None as input, or emit None as a result, the type annotations on the function should capture that.
Union Types
| Annotation | Mechanism | Resolves to |
|---|---|---|
T | None (any resolvable T) | direct resolve, wrapped nullable | nullable T |
bytes | bytearray | trivial equal-resolution (both independently resolve to the same DataType) | VARBINARY(MAX) |
Two structurally identical composites (dataclass / NamedTuple / TypedDict / Annotated[X, DataType]) | trivial equal-resolution (same fields, same types, same order) | the common ROW |
Outside of these examples, we need to consider type annotations that have a union over dissimilar types, like str | int. For result types, these all union types would throw an exception (sans Optional), as a UDF needs to declare a concrete return type. For input types, however, we could support this through the use of OrArgumentTypeStrategy, which allows us to represent this particular case.
Instead of shipping a flat list of DataTypes over the gateway, with one per argument, we would need to support shipping over a list of DataTypes per argument. We would also need to change the relevant classes, like PythonScalarFunction, to support being able to add the Or strategy when needed. To make the example concrete, the following function signature:
@udf() def f(a: int, b: int | str, c: str): ...
Would cross the bridge as:
inputTypes = [
[BIGINT NOT NULL],
[BIGINT NOT NULL, VARCHAR(2147483647) NOT NULL],
[VARCHAR(2147483647) NOT NULL],
]
Which would then be composed to the following type strategy in, for example, PythonScalarFunction:
InputTypeStrategies.sequence(
InputTypeStrategies.explicit(BIGINT NOT NULL),
new OrArgumentTypeStrategy(List.of(
InputTypeStrategies.explicit(BIGINT NOT NULL),
InputTypeStrategies.explicit(VARCHAR(2147483647) NOT NULL))),
InputTypeStrategies.explicit(VARCHAR(2147483647) NOT NULL))
Any Types
In Python type hinting, users are able to use Any to signify that they are, more or less, opting out of the type checking system. Similar to Union types above, we propose to handle this for input types but not result types, where a concrete type is needed.
An Any annotated parameter crosses the bridge as null for that argument's position specifically. This is mapped to an AnyArgumentTypeStrategy for that one position, leaving its sibling arguments concretely typed. Note this is a full opt-out for that parameter, not just of the concrete type but of nullability enforcement too.
Resolution Order
Where a type can come from in this schema can be more than one place. Type resolution follows this order, so that resolution-from-inference only ever fills in gaps in what would otherwise fail today.
- An explicit decorator argument (
input_types,result_type, etc). - For
AggregateFunction/TableAggregateFunctiononly: an overriddenget_result_type()/get_accumulator_type()method. - A type hint annotated with a
DataType, e.g,x: Annotated[int, DataTypes.TINYINT()]. - Type-hint inference from the relevant annotation.
- If none of the above apply, today's existing error behaviour is unchanged. A
TypeErrorwould be thrown for types that must be set (likeresult_type). For optional type declaration, likeinput_types, it would fall back to the existingWILDCARDresolution.
Function Examples
Scalar Functions
Scalar functions would operate fairly straightforwardly, where the input types and output type are just directly inferred:
@udf()
def repeat_string(count: int, text: str) -> str:
return text * count
Would produce input types of BIGINT and STRING, and an output type of STRING.
Table Functions
Iterator[T] whereby T is pulled out of the type signature.
With Table Functions, the input types would be inferred similar to the scalar function case, but the output type would need to be inferred from the Iterator[T], Iterable[T] or Generator[T,...] type, where T is then resolved to be the output type. For example:
from typing import Iterator, Tuple
class Split(TableFunction):
def eval(self, string: str) -> Iterator[Tuple[str, int]]:
for s in string.split(" "):
yield s, len(s)
Would infer input types of STRING and output types of [STRING, BIGINT]. This inference would also work with Iterable[x] and Generator[x, ...].
If declaring a table function via the decorator, a similar example would look like:
from typing import Iterator, Tuple
@udtf()
def split(string: str) -> Iterator[Tuple[str, int]]:
for s in string.split(" "):
yield s, len(s)
Aggregate Functions
Aggregate functions need an accumulator type, as well as a return type. The inference will pull the former from the return type of the create_accumulator, and the latter from the return type of get_value.
from dataclasses import dataclass
from typing import Optional
@dataclass
class WeightedAvgAccumulator:
total: int
count: int
class WeightedAvg(AggregateFunction):
def create_accumulator(self) -> WeightedAvgAccumulator:
return WeightedAvgAccumulator(0, 0)
def get_value(self, accumulator: WeightedAvgAccumulator) -> Optional[float]:
if accumulator.count == 0:
return None
else:
return accumulator.total / accumulator.count
def accumulate(self, accumulator: WeightedAvgAccumulator, value: float, weight: float):
accumulator.total += value * weight
accumulator.count += weight
def retract(self, accumulator: WeightedAvgAccumulator, value: float, weight: float):
accumulator.total -= value * weight
accumulator.count -= weight
This example would infer the accumulator type by translating the dataclass into a row, resulting in ROW<total BIGINT NOT NULL, count BIGINT NOT NULL> NOT NULL. The result type would be inferred to be a DOUBLE.
The function's SQL input types come from accumulate's parameters, excluding self and accumulator. In this case, value and weight, both resolving to DOUBLE NOT NULL. accumulate and retract both declare accumulator: WeightedAvgAccumulator; the consistency check applies to every accumulator-receiving method (accumulate, retract, and merge, where implemented) against create_accumulator's resolved type, raising a TypeError on any mismatch. The same check applies to get_value's return annotation, if present, against whatever the function's result_type resolves to.
Table Aggregate Functions
In Table Aggregate functions, the inferred type accumulator type comes from the annotation on create_accumulator, and the inferred type for the result type comes from emit_value:
@dataclass
class TopOrder:
price: Optional[float]
order_id: Optional[str]
class TopOrderResult(NamedTuple):
rank: int
price: Optional[float]
order_id: Optional[str]
@udtaf(enforce_input_types=True)
class Top2Orders(TableAggregateFunction):
def create_accumulator(self) -> List[TopOrder]:
return [TopOrder(None, None), TopOrder(None, None)]
def accumulate(
self, accumulator: List[TopOrder], price: Optional[float], order_id: Optional[str]
) -> None:
if price is not None:
if accumulator[0].price is None or price > accumulator[0].price:
accumulator[1] = accumulator[0]
accumulator[0] = TopOrder(price, order_id)
elif accumulator[1].price is None or price > accumulator[1].price:
accumulator[1] = TopOrder(price, order_id)
def emit_value(self, accumulator: List[TopOrder]) -> Iterator[TopOrderResult]:
yield TopOrderResult(1, accumulator[0].price, accumulator[0].order_id)
yield TopOrderResult(2, accumulator[1].price, accumulator[1].order_id)
This would resolve the accumulator_type to ARRAY<ROW<price DOUBLE, order_id VARCHAR(2147483647)>> NOT NULL and the result_type to ROW<rank BIGINT NOT NULL, price DOUBLE, order_id VARCHAR(2147483647)> NOT NULL. The accumulator consistency check described above in Aggregate Functions applies here too, between create_accumulator and accumulate.
Async Functions
For async functions, like AsyncScalarFunction, type annotations would support the above demonstrated bare types, as well as supporting unwrapping from Coroutine and Awaitable for the output type. The following examples would resolve to the same output type:
class LookupBare(AsyncScalarFunction):
async def eval(self, key: str) -> Optional[str]:
return await self._client.get(key)
class LookupCoroutine(AsyncScalarFunction):
async def eval(self, key: str) -> Coroutine[Any, Any, Optional[str]]:
return await self._client.get(key)
class LookupAwaitable(AsyncScalarFunction):
async def eval(self, key: str) -> Awaitable[Optional[str]]:
return await self._client.get(key)
Overriding Types
In some cases, the inferred type might not be what the user desires. For example, though they write a UDF with an input type of int, which would be inferred to Datatypes.BIGINT, they might an actual input type of SMALLINT in the planner.
This FLIP proposes two ways of overriding this. First, is to treat input/result types specified in the UDF decorator as priority and only do type inference if they are missing. So, for example with UDFs that specify their input, accumulator and result types via decorator arguments, this would be done in the decorator:
@udf(
input_types=[DataTypes.SMALLINT()]
)
def add_ten(n: int) -> int:
return n + 10
Aggregate and Table Aggregate functions would also support overriding inferred types via their class override methods:
class WeightedAvg(AggregateFunction):
...
def get_result_type(self):
return 'BIGINT'
def get_accumulator_type(self):
return 'ROW<f0 BIGINT, f1 BIGINT>'
This setup is less than ideal if, for example, a user defines a UDF with several input arguments, but only needs to specify one of those argument's input type, as it would require writing input_types for all the arguments in the function signature.
To this end, this FLIP also proposes exposing phantom subclasses of builtins, which would carry a DataType factory as a class attribute, in a pyflink.table.typehints module. Fixed width types would just expose the type directly:
TinyInt = _type("TinyInt", int, DataTypes.TINYINT)
SmallInt = _type("SmallInt", int, DataTypes.SMALLINT)
Int = _type("Int", int, DataTypes.INT)
BigInt = _type("BigInt", int, DataTypes.BIGINT)
Float = _type("Float", float, DataTypes.FLOAT)
Double = _type("Double", float, DataTypes.DOUBLE)
And parameterised types would expose a constructor:
def Decimal(precision: int, scale: int) -> type:
return _type(
f"Decimal_{precision}_{scale}",
decimal.Decimal,
functools.partial(DataTypes.DECIMAL, precision, scale),
)
The user would then be able to use the types, and generate parameterised ones on demand for their own types:
from dataclasses import dataclass
from typing import Optional
from pyflink.table import udf
from pyflink.table.typehints import TinyInt, SmallInt, Decimal
Money = Decimal(18, 2)
@dataclass
class PricingResult:
final_price: Money
discount_applied: bool
tier: TinyInt
@udf()
def apply_discount(
price: Money,
discount_pct: Optional[SmallInt],
tier: TinyInt,
) -> PricingResult:
pct = discount_pct or 0
discount = price * pct / 100
return PricingResult(
final_price=price - discount,
discount_applied=pct > 0,
tier=tier,
)
Compatibility, Deprecation, and Migration Plan
Initially, the type inference would ship with an enforce_input_types flag with a default of false. Then, after it has proved useful and stable, a deprecation warning on whether if a parameter is annotated but input types are not enforced, with a statement that this will change in future versions. Then, a switch of enforce_input_types to be default true, changing the flag to an opt out.
Test Plan
- Type resolution: one test per entry across the three type tables and the Union cases, covering all four UDF kinds.
- Or-strategy resolution (planner integration): a Union-typed parameter resolves correctly per call site. Matching type takes no cast, castable type picks the right branch, incompatible type is rejected.
- Backward compatibility (regression): explicit decorator arguments and existing
get_result_type()/get_accumulator_type()overrides both take precedence over inference and the existing PyFlink UDF test suite passes unmodified.
Rejected Alternatives
Nullable By Default
A rejected alternative was to keep Flink's nullable-by-default stance and treat every annotation as nullable regardless of Optional[T], instead offering a NotNull[T] escape hatch for users who want strictness:
def add_one(x: NotNull[int]) -> NotNull[int]:
return x + 1
This was rejected for the same reason given above in the Proposed Changes section. It inverts the default, requiring users to opt into what should be the common case, rather than making non-nullability the default and nullability (via Optional[T]) the explicit exception.
Overriding Type Inference Via Annotated
One alternative for letting UDF writers specify the concrete type was via the use of typing.Annotated:
from typing import Annotated as A
def add_ten(n: A[int, DataTypes.SMALLINT()]) -> A[int, DataTypes.SMALLINT()]:
return n + 10
This was ultimately discarded because it resulted in too many ambiguities, especially when the DataTypes are nullable by default (for example, how one should parse Optional[Annotated[int, DataTypes.SMALLINT()]]).
Out Of Scope
Pandas/Vectorized UDFs
Missing from this FLIP is handling Pandas/Vectorized UDFs, denoted by func_type='pandas'. We consider this out of scope for this FLIP. Inference would not apply with these functions, and they should be addressed in a follow up FLIP.
Handling *args, **kwargs
The inference schema above only handles fixed, named arguments. Handling annotated *args, or handling **kwargs with Unpack, is out of scope of this initial FLIP and is left for future work.