Python models
The `@model` decorator, execution context, dependencies, blueprinting, and DataFrame examples for Python models.
Use Python models when SQL does not fit: machine learning, calling external APIs, or complex business logic that is hard to express in SQL.
Vulcan supports Python models. Your function must return a Pandas, Spark, Bigframe, or Snowpark DataFrame.
When to use Python models:
Building machine learning workflows
Integrating with external APIs
Complex transformations that are easier in Python
Data processing that benefits from Python libraries
Definition
Create a Python model by adding a .py file to your models/ directory and defining an execute function.
A basic Python model looks like this:
How it works:
The @model decorator captures your model's metadata (like the MODEL DDL in SQL models). You specify column names and types in the columns argument. This is required because Vulcan needs to create the table before your function runs.
Function signature: your execute function receives:
context: ExecutionContext: for running queries and getting time intervalsstart,end: time range for incremental modelsexecution_time: when the model is running**kwargs: any other runtime variables
Return types: you can return Pandas, PySpark, Bigframe, or Snowpark DataFrames. If your output is large, you can also use Python generators to return data in chunks for memory management.
Python dependencies
If your Python model (or engine-side UDF) needs additional Python packages, build a wheel and place it in your project under dependencies/python/.
Place wheels (and/or packages) at your project root under dependencies/python/. Nested folders under dependencies/python/ are supported.
In standard Vulcan execution flows (for example, local Docker or cloned-project execution), drop wheels into dependencies/python/ and import them normally in your model or UDF code.
@model specification
The @model decorator accepts the same properties as SQL models. Use Python syntax instead of SQL DDL. name, kind, cron, grains, and the rest work the same way.
You specify Python model kinds with a Python dictionary containing the kind's name and arguments. Find all model kind arguments in the models configuration reference page.
The model configuration reference documents all model kind properties.
Supported kind dictionary name values are:
ModelKindName.VIEWModelKindName.FULLModelKindName.SEEDModelKindName.INCREMENTAL_BY_TIME_RANGEModelKindName.INCREMENTAL_BY_UNIQUE_KEYModelKindName.INCREMENTAL_BY_PARTITIONModelKindName.SCD_TYPE_2_BY_TIMEModelKindName.SCD_TYPE_2_BY_COLUMNModelKindName.EMBEDDEDModelKindName.CUSTOMModelKindName.EXTERNAL
Execution context
Python models can do anything you want, but all models should be idempotent. Python models can fetch data from upstream models or data outside of Vulcan.
Fetching data: use context.fetchdf() to run SQL queries and get DataFrames:
Resolving table names: use context.resolve_table() to get the correct table name for the current environment (it handles dev/prod prefixes automatically):
Best practice: make your models idempotent. Running them multiple times should produce the same result. This makes debugging and restatements much easier.
Optional pre/post-statements
You can run SQL commands before and after your Python model executes. Use this to set session parameters, create indexes, or run data quality checks.
Pre-statements: run before your execute function. Post-statements: run after your execute function completes.
Pass SQL strings, SQLGlot expressions, or macro calls as lists to pre_statements and post_statements.
Project-level defaults: you can define pre/post-statements in model_defaults for consistent behavior across all models. Default statements run first, then model-specific ones. Learn more in the model configuration reference.
The previous example's post_statements called the user-defined Vulcan macro @CREATE_INDEX(@this_model, id).
You can define the CREATE_INDEX macro in the project's macros directory like this. The macro creates a table index on a single column, conditional on the runtime stage being creating (table creation time).
Alternative approach: instead of using the @model decorator's pre_statements and post_statements, you can execute SQL directly in your function using context.engine_adapter.execute().
Important: if you want post-statements to run after your function completes, use yield instead of return. Post-statements specified after a yield execute after the function finishes.
This example function includes both pre- and post-statements:
Optional on-virtual-update statements
On-virtual-update statements run when Vulcan creates or updates views in the virtual layer. This happens after Vulcan creates your model's physical table and sets up the view pointing to it.
Common use case: granting permissions on views so users can query them.
You can set on_virtual_update in the @model decorator to a list of SQL strings, SQLGlot expressions, or macro calls.
Project-level defaults: you can define on-virtual-update statements at the project level using model_defaults in your configuration. These apply to all models in your project (including Python models) and merge with any model-specific statements. Default statements run first, followed by model-specific statements. Learn more in the model configuration reference.
Dependencies
To fetch data from an upstream model, first get the table name using context's resolve_table method. This returns the appropriate table name for the current runtime environment:
The resolve_table method automatically adds the referenced model to the Python model's dependencies.
The only other way to set dependencies in Python models is to define them explicitly in the @model decorator with the keyword depends_on. Dependencies you define in the model decorator take precedence over any dynamic references inside the function.
You can use global variables or blueprint variables in resolve_table calls:
Returning empty DataFrames
Python models cannot return empty DataFrames directly. If your model might return empty data, use yield instead of return:
Why? This lets Vulcan handle the empty case properly. If you return an empty DataFrame, Vulcan errors. If you yield an empty generator or conditionally yield, it works fine.
User-defined variables
You can access user-defined global variables from within the Python model with the context.var method.
For example, this model accesses the user-defined variables var and var_with_default. It specifies a default value of default_value if variable_with_default resolves to a missing value.
Alternatively, you can access global variables via execute function arguments, where the name of the argument corresponds to the name of a variable key.
For example, this model specifies my_var as an argument to the execute method. The model code can reference the my_var object directly:
Make sure the argument has a default value if the variable might be missing.
Specify arguments explicitly: you cannot access variables using kwargs.
Python model blueprinting
Python models can serve as templates for creating multiple models. This is called blueprinting: you define 1 model template, and Vulcan creates multiple models from it.
How it works: parameterize the model name with a variable (using @{variable} syntax) and provide a list of mappings in blueprints. Vulcan creates 1 model for each mapping.
Use case: when you have similar models that differ only by a few parameters (such as different schemas, regions, or customers).
This example creates 2 models:
Important: notice the @{customer} syntax in the model name. The curly braces tell Vulcan to treat the variable value as a SQL identifier (not a string literal). Learn more about this syntax here.
Dynamic blueprints: you can generate blueprints dynamically using macros. Use this when your blueprint list comes from external sources (such as CSV files or API calls):
For example, the definition of gen_blueprints looks like this:
You can also use the @EACH macro, combined with a global list variable (@values):
Using macros in model properties
Python models support macro variables in model properties, but there is a gotcha when macros appear inside strings.
The issue: cron expressions often use @ (such as @daily, @hourly), which conflicts with Vulcan's macro syntax.
The solution: wrap the entire expression in quotes and prefix with @:
This is necessary because cron expressions often use @ for aliases (such as @daily, @hourly), which conflicts with Vulcan's macro syntax.
Examples
Practical examples showing different ways to use Python models.
Basic
A simple Python model that returns a static Pandas DataFrame. All metadata properties work the same as SQL models. Use Python syntax.
SQL query and Pandas
A more realistic example: query upstream models, do some pandas processing, and return the result. This shows how to use Python models in practice:
PySpark
If you use Spark, use the PySpark DataFrame API instead of Pandas. PySpark DataFrames compute in a distributed fashion (across your Spark cluster), which is much faster for large datasets.
Why PySpark over Pandas: Pandas loads everything into memory on a single machine. PySpark distributes the work across your cluster, so you can handle much larger datasets.
Snowpark
If you use Snowflake, use the Snowpark DataFrame API. Like PySpark, Snowpark DataFrames compute on Snowflake's servers (not locally), which is much more efficient.
Why Snowpark over Pandas: all computation happens in Snowflake, so you are not moving data to your local machine. Faster, cheaper, and can handle huge datasets.
Batching
If your Python model outputs a huge DataFrame and you cannot use Spark, Bigframe, or Snowpark, batch the output using Python generators.
The problem: with Pandas, everything loads into memory. If your output is too large, you run out of memory.
The solution: use yield to return DataFrames in chunks. Vulcan processes them one at a time, so you never have more than one chunk in memory at once.
Here is how to do it:
Serialization
Vulcan executes Python models locally (wherever Vulcan is running) using a custom serialization framework. Your Python code runs on your machine or CI/CD environment, not in the database.
Why this matters: you have full access to Python libraries, can make API calls, and run ML processing. The database receives only the final DataFrame.
Last updated
Was this helpful?