Ulysse Petit
03/22/2025, 11:20 PMMarvin
03/22/2025, 11:20 PMprefect variable set
to create or update variables.
2. Access Variables in Python Code:
- Use Prefect's Python SDK to interact with these variables. You can retrieve variable values using methods like get
within your flow or task functions.
- Example:
python
from prefect import flow, task
from prefect.variables import get
@task
def my_task():
my_var = get('MY_VARIABLE_NAME')
print(f"Variable value: {my_var}")
@flow
def my_flow():
my_task()
if __name__ == "__main__":
my_flow()
3. Use Variables in Prefect YAML:
- For deployments, you can define variables in prefect.yaml
files or pass them as job variables during deployment.
For more details, you can refer to the Prefect documentation on variables and customizing infrastructure.
Remember, these methods assume you are using Prefect 3.x, as it has specific features for variable management.Ulysse Petit
03/23/2025, 9:19 AMmy_variable = "something"
def function():
print(my_variable)
How to do that with Prefect?Marvin
03/23/2025, 9:19 AMpython
# Define a global variable
my_variable = "something"
from prefect import flow, task
@task
def function():
# Access the global variable
print(my_variable)
@flow
def my_flow():
function()
if __name__ == "__main__":
my_flow()
### Key Points:
- Global Scope: The variable my_variable
is defined at the top level of the script, making it accessible within the function
task.
- No Special Prefect Handling Required: Prefect tasks and flows can access global variables defined in the same script without any special handling.
This approach works seamlessly with Prefect as it does with any standard Python script, allowing you to maintain an imperative programming style.