Writing a model in Python instead of SQL
dbt supports Python models as an alternative to SQL for transformations that are easier to express in Python, such as complex statistical logic or use of ML libraries. Python models are defined in .py files and must return a DataFrame, but they run on the data platform's compute (not dbt's), so they only work with adapters that support this feature (Snowflake, Databricks, BigQuery).
1 · Learn the must-know
- A Python model must define a function named model(dbt, session) that returns a DataFrame (pandas, Spark, or Snowpark, depending on platform).
- Use dbt.ref() and dbt.source() inside the Python model function to reference other models and sources, just as you would with Jinja in SQL models.
- Python models support the same node configs as SQL models (materialized, tags, schema, etc.), typically set via dbt.config() calls inside the model function or in a .yml/config block.
- Only table and incremental materializations are supported for Python models; view and ephemeral materializations are not supported.
- Python models are only supported on Snowflake, Databricks, and BigQuery (via Dataproc); other adapters like Postgres/Redshift do not support them.
- Because Python models execute as separate jobs on the warehouse's compute (e.g., Snowpark, PySpark), they can be slower to run and iterate on than SQL models, so SQL should still be preferred for simple transformations.
2 · Check your understanding
You create a new file at models/customer_scores.py and want dbt to build it as a model. Which function signature must the file define so that dbt run can execute it?
What you have tried across dbt Analytics Engineering's objectives, not a readiness score.
Developing and optimizing dbt models45.16% of the exam*0 of 14 tried
Managing dbt models governance9.68% of the exam*0 of 3 tried
Debugging data modeling errors16.13% of the exam*0 of 5 tried
Troubleshooting and optimizing dbt pipelines6.45% of the exam*0 of 2 tried
Implementing dbt tests9.68% of the exam*0 of 3 tried
Implementing and maintaining external dependencies6.45% of the exam*0 of 2 tried
Leveraging the dbt state6.45% of the exam*0 of 2 tried
* Our estimate. dbt Labs publishes no section weights.
3 · Keep going
Ready for more? Take a weighted mock or try free practice questions.