如何在dbt Python模型中导入自定义模块?遇__init__.py兼容问题
dbt Python模型导入自定义模块问题解决
问题原因
- 导入路径完全错误:你写的
from test.filter_out import filter_out里的test包在你的目录结构中根本不存在,路径和实际文件位置不匹配,自然找不到目标模块。 - init.py破坏dbt逻辑:dbt识别模型依赖自身的文件扫描规则,而非Python标准包结构。在model目录下添加
__init__.py会让Python将该目录视为标准Python包,干扰dbt的模型加载流程,导致dbt无法正常工作。
解决方案
方法1:使用相对导入
基于两个文件的目录层级,在sample_model.py中使用相对导入语句:
from ...some_domain.filter_out import filter_out
说明:sample_model.py位于modelling/model/schema/,...表示向上回溯两级目录到modelling/,之后就能定位到some_domain下的filter_out.py。
方法2:手动添加路径到模块搜索列表
如果相对导入出现执行异常,可以在sample_model.py开头添加代码,将modelling目录加入Python的模块搜索路径:
import sys from pathlib import Path # 获取modelling目录的绝对路径 modelling_dir = str(Path(__file__).parent.parent.parent) if modelling_dir not in sys.path: sys.path.append(modelling_dir) from some_domain.filter_out import filter_out
说明:Path(__file__)指向当前sample_model.py文件,通过多次parent调用回溯到modelling目录,将其加入sys.path后,就可以直接从some_domain导入目标模块。
内容的提问来源于stack exchange,提问作者Sam777
相关产品推荐
相关产品推荐

