```python:inference/core/workflows/execution_engine/v1/dynamic_blocks/block_scaffolding.py
import types
from typing import Optional

from inference.core.env import (MODAL_ANONYMOUS_WORKSPACE_NAME,
                                WORKFLOWS_CUSTOM_PYTHON_EXECUTION_MODE)
from inference.core.exceptions import WorkspaceLoadError
from inference.core.roboflow_api import get_roboflow_workspace
from inference.core.workflows.errors import PythonBlockError
from inference.core.workflows.execution_engine.v1.dynamic_blocks.entities import \
    PythonCode

IMPORTS_LINES = [
    "from typing import Any, List, Dict, Set, Optional",
    "import supervision as sv",
    "import numpy as np",
    "import math",
    "import time",
    "import json",
    "import os",
    "import requests",
    "import cv2",
    "import shapely",
    "from inference.core.workflows.execution_engine.entities.base import Batch, WorkflowImageData",
    "from inference.core.workflows.prototypes.block import BlockResult",
]

# Shared globals dict for all custom python blocks in local mode
_LOCAL_SHARED_GLOBALS = {}



# Cached generated imports string keyed by tuple(imports)
_IMPORTS_CACHE = {}

# Cached compiled code objects keyed by source string
_COMPILED_CODE_CACHE = {}


def extract_code_snippet(
    code: Optional[str], error_line: int, context: int = 10
) -> str:
    """Extract a code snippet around the error line with markers."""
    if not code:
        return ""

    lines = code.splitlines()
    error_idx = error_line - 1
    start = max(0, error_idx - context)
    end = min(len(lines), error_idx + context + 1)
    snippet_lines = [
        f"{'>>>' if i == error_idx else '   '} {i + 1}: {lines[i]}"
        for i in range(start, end)
    ]
    return "\n" + "\n".join(snippet_lines)


def _get_python_code_imports(python_code: PythonCode) -> str:
    return "\n".join(IMPORTS_LINES) + "\n" + "\n".join(python_code.imports) + "\n\n"




def _build_imports_string_cached(python_code: PythonCode) -> str:
    # Use tuple(...) as a hashable key; handle None imports gracefully
    imports_list = tuple(python_code.imports or ())
    cached = _IMPORTS_CACHE.get(imports_list)
    if cached is not None:
        return cached
    # Build imports string (same format as original helper)
    # Keep original behavior by delegating to existing function for formatting
    imports_str = _get_python_code_imports(python_code)
    _IMPORTS_CACHE[imports_list] = imports_str
    return imports_str


def _compile_source_cached(source: str):
    compiled = _COMPILED_CODE_CACHE.get(source)
    if compiled is not None:
        return compiled
    # Use "<string>" filename to preserve traceback behavior consistent with exec(source, ...)
    compiled_code = compile(source, "<string>", "exec")
    _COMPILED_CODE_CACHE[source] = compiled_code
    return compiled_code


def create_dynamic_module(
    block_type_name: str,
    python_code: PythonCode,
    module_name: str,
    api_key: Optional[str] = None,
    skip_class_eval: Optional[bool] = False,
) -> types.ModuleType:

    if skip_class_eval:
        # Create a stub module for local reference
        dynamic_module = types.ModuleType(module_name)
        # Add placeholder function
        setattr(
            dynamic_module, python_code.run_function_name, lambda *args, **kwargs: None
        )
        if python_code.init_function_code:
            setattr(dynamic_module, python_code.init_function_name, lambda: {})
        return dynamic_module

    imports = _build_imports_string_cached(python_code)
    code = python_code.run_function_code
    if python_code.init_function_code:
        code = code + "\n\n" + python_code.init_function_code
    # Join imports and code together into source
    source = imports + code

    # If using Modal and local execution is disabled, validate code remotely

    # If using Modal and local execution is disabled, validate code remotely
    if WORKFLOWS_CUSTOM_PYTHON_EXECUTION_MODE == "modal":
        # Validate code in Modal sandbox for security
        from inference.core.workflows.execution_engine.v1.dynamic_blocks.modal_executor import \
            validate_code_in_modal

        try:  # Get workspace_id from context if available
            validation_workspace = get_roboflow_workspace(api_key)
        except WorkspaceLoadError:
            validation_workspace = None

        # Fall back to "anonymous" for non-authenticated users
        if not validation_workspace:
            validation_workspace = MODAL_ANONYMOUS_WORKSPACE_NAME

        # This will raise if validation fails
        validate_code_in_modal(python_code, validation_workspace)

        # Create a stub module for local reference
        dynamic_module = types.ModuleType(module_name)
        # Add placeholder function
        setattr(
            dynamic_module, python_code.run_function_name, lambda *args, **kwargs: None
        )
        if python_code.init_function_code:
            setattr(dynamic_module, python_code.init_function_name, lambda: {})
        return dynamic_module
    else:
        # Local validation and module creation
        try:
            dynamic_module = types.ModuleType(module_name)
            # Inject the shared globals dict into the module namespace
            dynamic_module.__dict__["globals"] = _LOCAL_SHARED_GLOBALS
            # Compile once and reuse compiled code objects when possible
            compiled = _compile_source_cached(source)
            exec(compiled, dynamic_module.__dict__)
            return dynamic_module
        except Exception as error:
            error_line = getattr(error, "lineno", None)
            code_snippet = None
            if error_line and python_code.run_function_code:
                snippet = extract_code_snippet(
                    python_code.run_function_code, error_line
                )
                code_snippet = snippet.lstrip("\n") if snippet else None

            raise PythonBlockError(
                message=f"{error.__class__.__name__}: {error}",
                block_type_name=block_type_name,
                error_line=error_line,
                code_snippet=code_snippet,
            ) from error
```