Snowpark Python UDF注册报错:未找到默认Session 请求协助
问题解决:Snowpark UDF注册时出现"No default Session is found"错误
错误原因
在Snowflake Python Worksheet中,顶级作用域的代码(main函数外)会在session初始化前执行。你的@udf装饰器写在main函数外,此时没有可用的默认session,导致UDF注册失败。另外main函数里的df变量未定义,这也是后续会触发的问题。
解决方案
把UDF的注册逻辑移到main函数内部,或者在@udf装饰器中显式传入session参数。以下是两种可行的修正方案:
方案1:将UDF注册移到main函数内
def main(session: snowpark.Session): # 在main内注册UDF,此时session已初始化完成 @session.udf(name='a_plus_b', input_types=[IntegerType(), IntegerType()], return_type=IntegerType(), is_permanent=False, replace=True) def a_plus_b(a: int, b: int) -> int: return a+b # 先定义df(示例:从指定表读取数据) df = session.table("your_target_table") # 注意:with_column返回新DataFrame,需重新赋值 df = df.with_column('Somme', a_plus_b(col('a'), col('b'))) return df
方案2:在装饰器中显式指定session
如果希望UDF在顶级作用域定义,需要通过session参数传入已激活的session:
from snowflake.snowpark.session import get_active_session # 获取当前激活的session session = get_active_session() @udf( name='a_plus_b', input_types=[IntegerType(), IntegerType()], return_type=IntegerType(), is_permanent=False, replace=True, session=session # 显式传入session参数 ) def a_plus_b(a: int, b: int) -> int: return a+b def main(session: snowpark.Session): # 定义df df = session.table("your_target_table") df = df.with_column('Somme', a_plus_b(col('a'), col('b'))) return df
额外注意点
with_column方法不会修改原DataFrame,而是返回新的对象,因此必须重新赋值给df。- 确保
df变量在main函数中被正确初始化(比如从表读取数据,或创建测试用DataFrame)。
内容的提问来源于stack exchange,提问作者sidy ahmed ndiaye
相关产品推荐
相关产品推荐

