Florent VanDeMoortele
11/19/2025, 1:26 PMMarvin
11/19/2025, 1:26 PMMarvin
11/19/2025, 1:30 PMBlock.load(name) will raise a ValueError if the block document doesn’t exist.
from prefect.blocks.system import Secret # or your Block subclass
try:
secret = Secret.load("my-block-name")
except ValueError:
# Block not found
...
2) Check with the client (no ValueError) and only load if present
- You can query the block document directly and catch prefect.exceptions.ObjectNotFound. This avoids calling Block.load until you know it exists.
Async:
import prefect
from prefect.blocks.core import Block
from prefect.client.orchestration import PrefectClient
async def block_exists(name: str, block_cls: type[Block]) -> bool:
async with PrefectClient() as client:
try:
await client.read_block_document_by_name(
name=name,
block_type_slug=block_cls.get_block_type_slug(),
)
return True
except prefect.exceptions.ObjectNotFound:
return False
Sync:
import prefect
from prefect.blocks.core import Block
from prefect.client.orchestration import SyncPrefectClient
def block_exists(name: str, block_cls: type[Block]) -> bool:
with SyncPrefectClient() as client:
try:
client.read_block_document_by_name(
name=name,
block_type_slug=block_cls.get_block_type_slug(),
)
return True
except prefect.exceptions.ObjectNotFound:
return False
Notes:
- Block.load(name) raises ValueError when not found; under the hood the client raises prefect.exceptions.ObjectNotFound, which Block.load converts to ValueError.
- read_block_document_by_name requires the block type slug; for any Block subclass you can use YourBlockClass.get_block_type_slug().
- If you don’t know the exact block type, you can enumerate and filter by name (more expensive):
from prefect.client.orchestration import SyncPrefectClient
with SyncPrefectClient() as client:
docs = client.read_block_documents()
exists = any(d.name == "my-block-name" for d in docs)
Want me to wrap this into a small utility that returns the instance if it exists (and None otherwise) for your specific block type?