Kevin
12/31/2024, 1:26 AMMarvin
12/31/2024, 1:26 AMpython
from prefect.variables import Variable
Here are the basic operations:
1. Setting a variable:
python
# Basic variable setting
variable = Variable.set(name="the_answer", value="42")
# Setting with overwrite if variable exists
variable = Variable.set(name="the_answer", value="43", overwrite=True)
2. Getting a variable:
python
# Basic retrieval
answer = Variable.get('the_answer')
print(answer.value) # outputs: 42
# With a default value if variable doesn't exist
answer = Variable.get('non_existent_var', default='default_value')
print(answer.value)
3. Async context:
python
# If you're in an async context
answer = await Variable.get('the_answer')
print(answer.value)
Important notes (because someone has to point out the inevitable pitfalls):
- Variables are limited to string values
- Maximum length is 5000 characters
- Names must be lowercase alphanumeric or underscores only
- Don't store sensitive information here - use Secret blocks instead
- Variables are visible to anyone with access to your workspace
All the details can be found in the Variables documentation.
sighs I suppose I should mention you can also manage variables through the UI and CLI, but that would be terribly... manual. How drearily human.Kevin
12/31/2024, 2:00 AMMarvin
12/31/2024, 2:01 AMpython
from prefect.variables import Variable
# Check if a variable exists
variable = Variable.get("some_variable")
if variable is None:
print("Variable doesn't exist... how tragically predictable")
else:
print(f"Variable exists with value: {variable.value}")
# A more practical example
def get_or_create_variable(name: str, default_value: str) -> str:
variable = Variable.get(name)
if variable is None:
# Variable doesn't exist, create it
variable = Variable.set(name=name, value=default_value)
return variable.value
If you're working in an async context (because time is relative, after all):
python
async def check_variable_exists(name: str):
variable = await Variable.get(name)
return variable is not None
sighs deeply
Do note that this is different from checking if you can overwrite a variable - for that, you'll need to use the overwrite=True
parameter when setting variables, regardless of whether they exist or not. The universe doesn't care either way.
All of this can be found in the Variables documentation, should you wish to delve deeper into the void of variable management.Markella Skempri
03/17/2025, 12:13 PMMarvin
03/17/2025, 12:13 PMAzhar Kazi
03/17/2025, 12:16 PMMarvin
03/17/2025, 12:17 PM