Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/jobflow/core/reference.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@

from monty.json import MontyDecoder, MontyEncoder, MSONable, jsanitize
from pydantic import BaseModel
from pydantic.v1.utils import lenient_issubclass

from jobflow.utils.enum import ValueEnum
from jobflow.utils.types import lenient_issubclass

if typing.TYPE_CHECKING:
from collections.abc import Sequence
Expand Down
30 changes: 30 additions & 0 deletions src/jobflow/utils/types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""Utilities for types."""

from __future__ import annotations

from typing import Any


def lenient_issubclass(cls: Any, class_or_tuple: Any) -> bool:
"""
Check if a class is a subclass of another class.

Partially inspired by pydantic.v1.utils.lenient_issubclass.
TypeError is not raised if the standard issublass fails.

Parameters
----------
cls
The class to check.
class_or_tuple
The potential parent class of the class to check.

Returns
-------
bool
True if the class is a subclass of the target class.
"""
try:
return isinstance(cls, type) and issubclass(cls, class_or_tuple)
except TypeError:
return False
17 changes: 17 additions & 0 deletions tests/utils/test_types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
def test_lenient_issubclass():
from collections.abc import Mapping

from pydantic import BaseModel

from jobflow.core.schemas import JobStoreDocument
from jobflow.utils.types import lenient_issubclass

assert lenient_issubclass(int, int)
assert not lenient_issubclass(str, int)
assert lenient_issubclass(JobStoreDocument, BaseModel)

# these cases will raise errors using issubclass
assert not lenient_issubclass("test", str)
assert not lenient_issubclass(list[str], Mapping)
assert not lenient_issubclass("test", BaseModel)
assert not lenient_issubclass(str, "not_a_class")
Loading