SQLAlchemy 2.0.4创建SQLite引擎抛出TypeError异常求助
解决SQLAlchemy 2.0.4中SQLite create_function参数过多的问题
问题分析
你遇到的TypeError: function takes at most 3 arguments (4 given),是因为SQLAlchemy 2.0版本对SQLite函数注册逻辑做了调整,导致自定义set_regexp函数向sqlite3.Connection.create_function传递了额外关键字参数,而低版本Python的sqlite3模块不支持这些参数,最终触发报错。
解决方案
方案1:简化函数调用
直接移除多余的**create_func_kw参数,修改set_regexp函数:
def set_regexp(dbapi_connection): dbapi_connection.create_function("regexp", 2, regexp)
方案2:兼容不同Python版本的参数传递
如果需要传递deterministic这类可选参数,先检查当前sqlite3.create_function支持的参数,再传递有效参数:
import inspect def set_regexp(dbapi_connection): create_func_kw = {"deterministic": True} # 过滤出当前sqlite3版本支持的关键字参数 sig = inspect.signature(dbapi_connection.create_function) valid_kwargs = {k: v for k, v in create_func_kw.items() if k in sig.parameters} dbapi_connection.create_function("regexp", 2, regexp, **valid_kwargs)
方案3:使用SQLAlchemy 2.0内置方式注册regexp
通过自定义SQLAlchemy函数并编译的方式,更适配2.0版本规范:
from sqlalchemy import create_engine from sqlalchemy.ext.compiler import compiles from sqlalchemy.sql.expression import FunctionElement # 定义自定义regexp函数 class regexp(FunctionElement): name = "regexp" # 为SQLite编译该函数 @compiles(regexp, "sqlite") def compile_regexp(element, compiler, **kw): return f"{compiler.process(element.clauses)} REGEXP ?" # 创建引擎并注册SQLite函数 engine = create_engine('sqlite://') with engine.connect() as conn: # 替换为你的regexp实现逻辑 conn.connection.create_function("regexp", 2, lambda expr, value: expr in value)
补充说明
SQLAlchemy 1.4.16中可能默认屏蔽了参数传递的冲突,而2.0版本更严格遵循sqlite3模块的API规范。如果你的Python版本低于3.8,sqlite3.create_function确实不支持deterministic等关键字参数,此时必须移除多余参数。
内容的提问来源于stack exchange,提问作者zeitghaist
相关产品推荐
相关产品推荐

