Skip to content

marvin_impl

Class info

Classes

Name Children Inherits
JSONSchema
schemez.schema_to_type.marvin_impl

    🛈 DocStrings

    Convert JSON schema to appropriate Python type with validation.

    Credits to Marvin / prefect for original code.

    create_array_type

    create_array_type(
        schema: Mapping[str, Any], schemas: Mapping[str, Any]
    ) -> type | Annotated[Any, ...]
    

    Create list/set type with optional constraints.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def create_array_type(
        schema: Mapping[str, Any], schemas: Mapping[str, Any]
    ) -> type | Annotated[Any, ...]:
        """Create list/set type with optional constraints."""
        items = schema.get("items", {})
        if isinstance(items, list):
            # Handle positional item schemas
            item_types = [schema_to_type(s, schemas) for s in items]
            combined = Union[tuple(item_types)]  # noqa: UP007
            base = list[combined]
        else:
            # Handle single item schema
            item_type = schema_to_type(items, schemas)
            base = set if schema.get("uniqueItems") else list
            base = base[item_type]
    
        constraints = {
            k: v
            for k, v in {
                "min_length": schema.get("minItems"),
                "max_length": schema.get("maxItems"),
            }.items()
            if v is not None
        }
    
        return Annotated[base, Field(**constraints)] if constraints else base
    

    create_dataclass

    create_dataclass(
        schema: Mapping[str, Any], name: str | None = None, schemas: Mapping[str, Any] | None = None
    ) -> type
    

    Create dataclass from object schema.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def create_dataclass(
        schema: Mapping[str, Any],
        name: str | None = None,
        schemas: Mapping[str, Any] | None = None,
    ) -> type:
        """Create dataclass from object schema."""
        name = name or schema.get("title")
        # Sanitize name for class creation
        sanitized_name = sanitize_name(name or "Root")
        cache_key = (hash_schema(schema), hash_schema(schemas or {}), sanitized_name)
    
        # Return existing class if already built
        with _classes_lock:
            if (existing := _classes.get(cache_key)) is not None:
                _classes.move_to_end(cache_key)
                return existing
        in_progress: set[tuple[str, str, str]] = _building.__dict__.setdefault("keys", set())
        if cache_key in in_progress:  # recursive reference while building it
            return ForwardRef(sanitized_name)  # ty: ignore[invalid-explicit-return]
        in_progress.add(cache_key)
        try:
            cls = _build_dataclass(schema, sanitized_name, schemas)
        finally:
            in_progress.discard(cache_key)
    
        with _classes_lock:
            _classes[cache_key] = cls
            while len(_classes) > _MAX_CACHED_CLASSES:
                _classes.popitem(last=False)
        return cls
    

    create_enum

    create_enum(name: str, values: list[Any]) -> type | Enum
    

    Create enum type from list of values.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def create_enum(name: str, values: list[Any]) -> type | Enum:
        """Create enum type from list of values."""
        if all(isinstance(v, str) for v in values):
            return Enum(name, {v.upper(): v for v in values})
        return Literal[tuple(values)]
    

    create_field_with_default

    create_field_with_default(field_type: type, default_value: Any, schema: dict[str, Any]) -> Any
    

    Create a field with simplified default handling.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def create_field_with_default(field_type: type, default_value: Any, schema: dict[str, Any]) -> Any:
        """Create a field with simplified default handling."""
        # Always use None as default for complex types
        if isinstance(default_value, (dict, list)) or default_value is None:
            return field(default=None)
    
        # For simple types, use the value directly
        return field(default=default_value)
    

    create_numeric_type

    create_numeric_type(
        base: type[int | float], schema: Mapping[str, Any]
    ) -> type | Annotated[Any, ...]
    

    Create numeric type with optional constraints.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def create_numeric_type(
        base: type[int | float], schema: Mapping[str, Any]
    ) -> type | Annotated[Any, ...]:
        """Create numeric type with optional constraints."""
        if "const" in schema:
            return Literal[schema["const"]]
    
        constraints = {
            k: v
            for k, v in {
                "gt": schema.get("exclusiveMinimum"),
                "ge": schema.get("minimum"),
                "lt": schema.get("exclusiveMaximum"),
                "le": schema.get("maximum"),
                "multiple_of": schema.get("multipleOf"),
            }.items()
            if v is not None
        }
    
        return Annotated[base, Field(**constraints)] if constraints else base
    

    create_string_type

    create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]
    

    Create string type with optional constraints.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def create_string_type(schema: Mapping[str, Any]) -> type | Annotated[Any, ...]:
        """Create string type with optional constraints."""
        if "const" in schema:
            return Literal[schema["const"]]
    
        if fmt := schema.get("format"):
            if fmt == "uri":
                return AnyUrl
            if fmt == "uri-reference":
                return str
            return FORMAT_TYPES.get(fmt, str)
    
        constraints = {
            k: v
            for k, v in {
                "min_length": schema.get("minLength"),
                "max_length": schema.get("maxLength"),
                "pattern": schema.get("pattern"),
            }.items()
            if v is not None
        }
    
        return Annotated[str, StringConstraints(**constraints)] if constraints else str
    

    get_default_value

    get_default_value(
        schema: dict[str, Any], prop_name: str, parent_default: dict[str, Any] | None = None
    ) -> Any
    

    Get default value with proper priority ordering.

    1. Value from parent's default if it exists
    2. Property's own default if it exists
    3. None.
    Source code in src/schemez/schema_to_type/marvin_impl.py
    def get_default_value(
        schema: dict[str, Any],
        prop_name: str,
        parent_default: dict[str, Any] | None = None,
    ) -> Any:
        """Get default value with proper priority ordering.
    
        1. Value from parent's default if it exists
        2. Property's own default if it exists
        3. None.
        """
        if parent_default is not None and prop_name in parent_default:
            return parent_default[prop_name]
        return schema.get("default")
    

    hash_schema

    hash_schema(schema: Mapping[str, Any]) -> str
    

    Generate a deterministic hash for schema caching.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def hash_schema(schema: Mapping[str, Any]) -> str:
        """Generate a deterministic hash for schema caching."""
        return hashlib.sha256(json.dumps(schema, sort_keys=True).encode()).hexdigest()
    

    jsonschema_to_type

    jsonschema_to_type(schema: Mapping[str, Any], name: str | None = None) -> type
    

    Convert JSON schema to appropriate Python type with validation.

    Parameters:

    Name Type Description Default
    schema Mapping[str, Any]

    A JSON Schema dictionary defining the type structure and validation rules

    required
    name str | None

    Optional name for object schemas. Only allowed when schema type is "object". If not provided for objects, name will be inferred from schema's "title" property or default to "Root".

    None

    Returns:

    Type Description
    type

    A Python type (typically a dataclass for objects) with Pydantic validation

    Raises:

    Type Description
    ValueError

    If a name is provided for a non-object schema

    Examples:

    Create a dataclass from an object schema:

    schema = {
        "type": "object",
        "title": "Person",
        "properties": {
            "name": {"type": "string", "minLength": 1},
            "age": {"type": "integer", "minimum": 0},
            "email": {"type": "string", "format": "email"}
        },
        "required": ["name", "age"]
    }
    
    Person = jsonschema_to_type(schema)
    # Creates a dataclass with name, age, and optional email fields:
    # @dataclass
    # class Person:
    #     name: str
    #     age: int
    #     email: str | None = None
    
    Person(name="John", age=30)

    Create a scalar type with constraints:

    schema = {
        "type": "string",
        "minLength": 3,
        "pattern": "^[A-Z][a-z]+$"
    }
    
    NameType = jsonschema_to_type(schema)
    # Creates Annotated[str, StringConstraints(min_length=3, pattern="^[A-Z][a-z]+$")]
    
    @dataclass
    class Name:
        name: NameType
    

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def jsonschema_to_type(schema: Mapping[str, Any], name: str | None = None) -> type:
        """Convert JSON schema to appropriate Python type with validation.
    
        Args:
            schema: A JSON Schema dictionary defining the type structure and validation rules
            name: Optional name for object schemas. Only allowed when schema type is "object".
                If not provided for objects, name will be inferred from schema's "title"
                property or default to "Root".
    
        Returns:
            A Python type (typically a dataclass for objects) with Pydantic validation
    
        Raises:
            ValueError: If a name is provided for a non-object schema
    
        Examples:
            Create a dataclass from an object schema:
            ```python
            schema = {
                "type": "object",
                "title": "Person",
                "properties": {
                    "name": {"type": "string", "minLength": 1},
                    "age": {"type": "integer", "minimum": 0},
                    "email": {"type": "string", "format": "email"}
                },
                "required": ["name", "age"]
            }
    
            Person = jsonschema_to_type(schema)
            # Creates a dataclass with name, age, and optional email fields:
            # @dataclass
            # class Person:
            #     name: str
            #     age: int
            #     email: str | None = None
            ```
            Person(name="John", age=30)
    
            Create a scalar type with constraints:
            ```python
            schema = {
                "type": "string",
                "minLength": 3,
                "pattern": "^[A-Z][a-z]+$"
            }
    
            NameType = jsonschema_to_type(schema)
            # Creates Annotated[str, StringConstraints(min_length=3, pattern="^[A-Z][a-z]+$")]
    
            @dataclass
            class Name:
                name: NameType
            ```
        """
        # Always use the top-level schema for references
        if schema.get("type") == "object":
            return create_dataclass(schema, name, schemas=schema)
        if name:
            msg = f"Can not apply name to non-object schema: {name}"
            raise ValueError(msg)
        return schema_to_type(schema, schemas=schema)
    

    merge_defaults

    merge_defaults(
        data: Mapping[str, Any],
        schema: Mapping[str, Any],
        parent_default: Mapping[str, Any] | None = None,
    ) -> dict[str, Any]
    

    Merge defaults with provided data at all levels.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def merge_defaults(
        data: Mapping[str, Any],
        schema: Mapping[str, Any],
        parent_default: Mapping[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Merge defaults with provided data at all levels."""
        # If we have no data
        if not data:
            # Start with parent default if available
            if parent_default:
                result = dict(parent_default)
            # Otherwise use schema default if available
            elif "default" in schema:
                result = dict(schema["default"])
            # Otherwise start empty
            else:
                result = {}
        # If we have data and a parent default, merge them
        elif parent_default:
            result = dict(parent_default)
            for key, value in data.items():
                if isinstance(value, dict) and key in result and isinstance(result[key], dict):
                    # recursively merge nested dicts
                    result[key] = merge_defaults(value, {"properties": {}}, result[key])
                else:
                    result[key] = value
        # Otherwise just use the data
        else:
            result = dict(data)
    
        # For each property in the schema
        for prop_name, prop_schema in schema.get("properties", {}).items():
            # If property is missing, apply defaults in priority order
            if prop_name not in result:
                if parent_default and prop_name in parent_default:
                    result[prop_name] = parent_default[prop_name]
                elif "default" in prop_schema:
                    result[prop_name] = prop_schema["default"]
    
            # If property exists and is an object, recursively merge
            if (
                prop_name in result
                and isinstance(result[prop_name], dict)
                and prop_schema.get("type") == "object"
            ):
                # Get the appropriate default for this nested object
                nested_default = None
                if parent_default and prop_name in parent_default:
                    nested_default = parent_default[prop_name]
                elif "default" in prop_schema:
                    nested_default = prop_schema["default"]
    
                result[prop_name] = merge_defaults(result[prop_name], prop_schema, nested_default)
    
        return result
    

    resolve_ref

    resolve_ref(ref: str, schemas: Mapping[str, Any]) -> Mapping[str, Any]
    

    Resolve JSON Schema reference to target schema.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def resolve_ref(ref: str, schemas: Mapping[str, Any]) -> Mapping[str, Any]:
        """Resolve JSON Schema reference to target schema."""
        path = ref.replace("#/", "").split("/")
        current = schemas
        for part in path:
            current = current.get(part, {})
        return current
    

    sanitize_name

    sanitize_name(name: str) -> str
    

    Convert string to valid Python identifier.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def sanitize_name(name: str) -> str:
        """Convert string to valid Python identifier."""
        # Step 1: replace everything except [0-9a-zA-Z_] with underscores
        cleaned = re.sub(r"[^0-9a-zA-Z_]", "_", name)
        # Step 2: deduplicate underscores
        cleaned = re.sub(r"__+", "_", cleaned)
        # Step 3: if the first char of original name isn't a letter, prepend field_
        if not name or not re.match(r"[a-zA-Z]", name[0]):
            cleaned = f"field_{cleaned}"
        # Step 4: deduplicate again and strip trailing underscores
        return re.sub(r"__+", "_", cleaned).strip("_")
    

    schema_to_type

    schema_to_type(schema: Mapping[str, Any], schemas: Mapping[str, Any]) -> type
    

    Convert schema to appropriate Python type.

    Source code in src/schemez/schema_to_type/marvin_impl.py
    def schema_to_type(schema: Mapping[str, Any], schemas: Mapping[str, Any]) -> type:  # noqa: PLR0911
        """Convert schema to appropriate Python type."""
        if not schema:
            return object
    
        if "type" not in schema and "properties" in schema:
            return create_dataclass(schema, schema.get("title", "<unknown>"), schemas)
    
        # Handle references first
        if "$ref" in schema:
            ref = schema["$ref"]
            # Handle self-reference
            if ref == "#":
                return ForwardRef(schema.get("title", "Root"))  # ty: ignore[invalid-explicit-return]
            return schema_to_type(resolve_ref(ref, schemas), schemas)
    
        if "const" in schema:
            return Literal[schema["const"]]
    
        if "enum" in schema:
            return create_enum(f"Enum_{next(_enum_counter)}", schema["enum"])  # ty: ignore[invalid-explicit-return]
    
        schema_type = schema.get("type")
        if not schema_type:
            return Any  # pyright: ignore[reportReturnType]
    
        if isinstance(schema_type, list):
            # Create a copy of the schema for each type, but keep all constraints
            types: list[type | Any] = []
            for t in schema_type:
                type_schema = dict(schema).copy()
                type_schema["type"] = t
                types.append(schema_to_type(type_schema, schemas))
            has_null = type(None) in types
            types = [t for t in types if t is not type(None)]
            if has_null:
                combined = Union[tuple(types)] if len(types) > 1 else types[0]  # noqa: UP007
                return combined | None  # ty: ignore[unsupported-operator]
            return Union[tuple(types)]  # type: ignore  # noqa: UP007
    
        return _get_from_type_handler(schema, schemas)(schema)