<@ULVA73B9P> how to check if Block instance exists...
# ask-marvin
f
@Marvin how to check if Block instance exists before loading it?
m
thought for 235.3 seconds
In Prefect 2.x there isn’t an “exists()” API on blocks. The two common patterns are: 1) Try/except around Block.load(...) -
Block.load(name)
will raise a ValueError if the block document doesn’t exist.
Copy code
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:
Copy code
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:
Copy code
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):
Copy code
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?