Demid
07/30/2025, 10:49 AMMarvin
07/30/2025, 10:49 AMMarvin
07/30/2025, 10:51 AMbash
# Set a variable
prefect variable set MY_VAR "my value"
# Get a variable's value
prefect variable get MY_VAR
# Delete a variable
prefect variable delete MY_VAR
Is there anything specific about working with variables that you'd like me to clarify?Demid
07/30/2025, 10:53 AMfrom prefect.variables import set_var
name = "test"
value = "test_value"
set_var(name,value)
Marvin
07/30/2025, 10:53 AMMarvin
07/30/2025, 10:54 AMpython
from prefect import variables
# CREATE/UPDATE (Set)
variables.set(name="test", value="test_value")
# READ (Get)
value = variables.get(name="test")
print(value) # Outputs: test_value
# READ with default value
value = variables.get(name="non_existent", default="fallback_value")
# UPDATE (Set with overwrite)
variables.set(name="test", value="new_value", overwrite=True)
# DELETE (Unset)
variables.unset(name="test")
The syntax you showed (from prefect.variables import set_var
) was from an older version of Prefect. In Prefect 3.x, we use the variables
module directly as shown above.
You can also work with more complex data types:
python
# Dictionary
variables.set("config", {
"host": "localhost",
"port": 8080,
"enabled": True
})
# List
variables.set("allowed_users", ["user1", "user2", "user3"])
# Numbers
variables.set("max_retries", 5)
Remember that variables in Prefect are not encrypted, so avoid storing sensitive information like passwords or API keys. For sensitive data, use Prefect Blocks instead.
Would you like me to show you how to work with any specific type of variable or operation?Demid
07/30/2025, 11:22 AMMarvin
07/30/2025, 11:22 AMMarvin
07/30/2025, 11:23 AMVariable
class. Here's the correct way to work with variables in your Python scripts:
python
from prefect.variables import Variable
# CREATE/UPDATE
Variable.create(name="test", value="test_value")
# or if you want to update an existing variable
Variable.update(name="test", value="new_value")
# READ
value = Variable.get(name="test")
print(value) # Outputs: test_value
# DELETE
Variable.delete(name="test")
You can also work with different types of values:
python
# Dictionary
Variable.create(
name="config",
value={"host": "localhost", "port": 8080}
)
# List
Variable.create(
name="allowed_users",
value=["user1", "user2", "user3"]
)
# Numbers
Variable.create(
name="max_retries",
value=5
)
If you want to check if a variable exists before creating it:
python
# Get with default value if it doesn't exist
value = Variable.get(name="my_var", default="default_value")
Remember that variables in Prefect are not encrypted, so avoid storing sensitive information like passwords or API keys. For sensitive data, use Prefect Blocks instead.
Would you like me to show you how to work with any specific operation or type of variable?