Introduction to Python UDFs | Snowflake Documentation (original) (raw)

You can write the handler for a user-defined function (UDF) in Python. Topics in this section describe how to design and write a Python handler. You’ll also find examples.

For an introduction to UDFs, including a list of languages in which you can write a UDF handler, refer to User-defined functions overview.

Once you have a handler, you create the UDF with SQL. For information on using SQL to create or call a UDF, refer toCreating a user-defined function or Executing a UDF.

Snowflake currently supports writing UDFs in the following versions of Python:

How a Python handler works

When a user calls a UDF, the user passes UDF’s name and arguments to Snowflake. Snowflake calls the associated handler code (with arguments, if any) to execute the UDF’s logic. The handler method then returns the output to Snowflake, which passes it back to the client.

For each row passed to a UDF, the UDF returns either a scalar (i.e. single) value or, if defined as a table function, a set of rows.

Python UDFs can contain both new code and calls to existing packages, allowing you both flexibility and code reuse. For example, if you already have data analysis code in Python, then you can probably incorporate that into a Python UDF handler.

Example

Code in the following example creates a UDF called addone with a handler method addone_py. The Python argument and return types are converted to and from SQL by Snowflake according to mappings described inSQL-Python Data Type Mappings.

CREATE OR REPLACE FUNCTION addone(i INT) RETURNS INT LANGUAGE PYTHON RUNTIME_VERSION = '3.9' HANDLER = 'addone_py' AS defaddonepy(i):returni+1def addone_py(i): return i+1defaddonepy(i):returni+1;

Design considerations

Keep in mind the following for designing a useful handler.

Handler coding

From basics to detailed examples, the following topics describe how to write a UDF handler in Python.