Skip to content

FHIR Types Utilities

Utility classes and functions for getting and validating FHIR types.

FHIRTypeError

Path: fhircraft.fhir.resources.datatypes.utils.FHIRTypeError

Bases: Exception

Raised when type checking or conversion fails.

get_complex_FHIR_type

get_complex_FHIR_type(type_str: str, release='R4B') -> type
Source code in fhircraft/fhir/resources/datatypes/utils.py
def get_complex_FHIR_type(type_str: str, release="R4B") -> type:
    # Dynamically import the complex types module for the specified FHIR release
    complex_FHIR_types = importlib.import_module(
        f"fhircraft.fhir.resources.datatypes.{release}.complex"
    )
    model: type[FHIRBaseModel] = getattr(complex_FHIR_types, type_str)
    if not model.__pydantic_complete__:
        model.model_rebuild()  # type: ignore
    return model

get_fhir_primitive_type

get_fhir_primitive_type(type_str: str) -> type | None
Source code in fhircraft/fhir/resources/datatypes/utils.py
def get_fhir_primitive_type(type_str: str) -> type | None:
    return getattr(primitives, type_str, None)

get_fhir_resource_type

get_fhir_resource_type(type_str: str, release='R4B') -> type
Source code in fhircraft/fhir/resources/datatypes/utils.py
def get_fhir_resource_type(type_str: str, release="R4B") -> type:
    # Convert CamelCase to snake_case for module lookup
    resource_module = importlib.import_module(
        f"fhircraft.fhir.resources.datatypes.{release}.core"
    )

    resource = getattr(resource_module, type_str, None)
    if not resource:
        # Try to get from factory cache using lazy import to avoid circular dependency
        try:
            from fhircraft.fhir.resources import factory

            resource = next(
                (
                    model
                    for model in factory.factory.construction_cache.values()
                    if model.__name__ == type_str
                    and release
                    == get_FHIR_release_from_version(getattr(model, "fhirVersion", ""))
                ),
                None,
            )
        except ImportError:
            # Factory not available, which is fine - we'll just fail gracefully
            pass

        if not resource:
            raise AttributeError(f"Unknown {release} FHIR resource type: {type_str}")
    return resource

get_fhir_type

get_fhir_type(type_str: str, release='R4B') -> Any

Get the FHIR type (primitive, complex, or resource) by its string name.

Parameters:

Name Type Description Default
type_str str

The FHIR type name.

required
release str

The FHIR release version (default: "R4B").

'R4B'

Returns:

Name Type Description
type Any

The corresponding FHIR type class.

Raises:

Type Description
AttributeError

If the type is not found.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def get_fhir_type(type_str: str, release="R4B") -> Any:
    """
    Get the FHIR type (primitive, complex, or resource) by its string name.

    Args:
        type_str (str): The FHIR type name.
        release (str): The FHIR release version (default: "R4B").

    Returns:
        type: The corresponding FHIR type class.

    Raises:
        AttributeError: If the type is not found.
    """
    # First check for primitive types
    primitive_type = get_fhir_primitive_type(type_str)
    if primitive_type:
        return primitive_type

    # Next check for complex types
    try:
        complex_type = get_complex_FHIR_type(type_str, release)
        return complex_type
    except AttributeError:
        pass

    # Finally check for resource types
    try:
        resource_type = get_fhir_resource_type(type_str, release)
        return resource_type
    except AttributeError:
        pass

    raise AttributeError(f"Unknown FHIR type: {type_str}")

get_primitive_type_by_name

get_primitive_type_by_name(type_name: str) -> Union[TypeAliasType, None]

Get a FHIR primitive type by its string name.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def get_primitive_type_by_name(type_name: str) -> Union[TypeAliasType, None]:
    """Get a FHIR primitive type by its string name."""
    return getattr(primitives, type_name, None)

get_primitive_type_name

get_primitive_type_name(fhir_type: TypeAliasType) -> str

Get the string name of a FHIR primitive type.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def get_primitive_type_name(fhir_type: TypeAliasType) -> str:
    """Get the string name of a FHIR primitive type."""
    if hasattr(fhir_type, "__name__"):
        return fhir_type.__name__
    # Fallback: search primitives module
    for name in dir(primitives):
        if getattr(primitives, name) is fhir_type:
            return name
    return "Unknown"

is_base64binary

is_base64binary(value: Any) -> bool

Check if value is a valid FHIR Base64Binary.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_base64binary(value: Any) -> bool:
    """Check if value is a valid FHIR Base64Binary."""
    return is_fhir_primitive_type(value, primitives.Base64Binary)

is_boolean

is_boolean(value: Any) -> bool

Check if value is a valid FHIR Boolean.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_boolean(value: Any) -> bool:
    """Check if value is a valid FHIR Boolean."""
    return is_fhir_primitive_type(value, primitives.Boolean)

is_canonical

is_canonical(value: Any) -> bool

Check if value is a valid FHIR Canonical.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_canonical(value: Any) -> bool:
    """Check if value is a valid FHIR Canonical."""
    return is_fhir_primitive_type(value, primitives.Canonical)

is_code

is_code(value: Any) -> bool

Check if value is a valid FHIR Code.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_code(value: Any) -> bool:
    """Check if value is a valid FHIR Code."""
    return is_fhir_primitive_type(value, primitives.Code)

is_date

is_date(value: Any) -> bool

Check if value is a valid FHIR Date.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_date(value: Any) -> bool:
    """Check if value is a valid FHIR Date."""
    return (
        is_fhir_primitive_type(value, primitives.Date)
        if isinstance(value, str)
        else isinstance(value, date) and not isinstance(value, datetime)
    )

is_datetime

is_datetime(value: Any) -> bool

Check if value is a valid FHIR DateTime.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_datetime(value: Any) -> bool:
    """Check if value is a valid FHIR DateTime."""
    return (
        is_fhir_primitive_type(value, primitives.DateTime)
        if isinstance(value, str)
        else isinstance(value, datetime)
    )

is_decimal

is_decimal(value: Any) -> bool

Check if value is a valid FHIR Decimal.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_decimal(value: Any) -> bool:
    """Check if value is a valid FHIR Decimal."""
    return is_fhir_primitive_type(value, primitives.Decimal)

is_fhir_complex_type

is_fhir_complex_type(value: Any, fhir_type: FHIRBaseModel | type | str, raise_on_error: bool = True) -> bool

Check if a value conforms to a complex FHIR type.

Parameters:

Name Type Description Default
value Any

The value to check

required
fhir_type FHIRBaseModel | type | str

The complex FHIR type (or name thereof) to check against

required
raise_on_error bool

Whether to raise FHIRTypeError on unknown type (default: True)

True

Returns:

Name Type Description
bool bool

True if the value conforms to the type, False otherwise

Raises:

Type Description
FHIRTypeError

If the fhir_type is a string and does not correspond to a known complex type

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_fhir_complex_type(
    value: Any, fhir_type: "FHIRBaseModel | type | str", raise_on_error: bool = True
) -> bool:
    """
    Check if a value conforms to a complex FHIR type.

    Args:
        value: The value to check
        fhir_type: The complex FHIR type (or name thereof) to check against
        raise_on_error: Whether to raise FHIRTypeError on unknown type (default: True)

    Returns:
        bool: `True` if the value conforms to the type, `False` otherwise

    Raises:
        FHIRTypeError: If the fhir_type is a string and does not correspond to a known complex type
    """
    if isinstance(fhir_type, str):
        try:
            fhir_type = get_complex_FHIR_type(fhir_type)
        except AttributeError:
            if raise_on_error:
                raise FHIRTypeError(f"Unknown complex FHIR type: {fhir_type}")
            else:
                return False
    if isinstance(value, BaseModel) and issubclass(fhir_type, BaseModel):
        return isinstance(value, fhir_type)
    try:
        if hasattr(fhir_type, "model_validate"):
            fhir_type.model_validate(value)  # type: ignore
        return True
    except ValidationError as e:
        return False

is_fhir_primitive

is_fhir_primitive(value: Any) -> bool

Check if a value is a FHIR primitive type.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_fhir_primitive(value: Any) -> bool:
    """Check if a value is a FHIR primitive type."""
    return (
        is_string(value)
        or is_boolean(value)
        or is_integer(value)
        or is_decimal(value)
        or is_date(value)
        or is_datetime(value)
        or is_time(value)
        or is_code(value)
        or is_uri(value)
        or is_url(value)
        or is_canonical(value)
        or is_base64binary(value)
        or is_instant(value)
        or is_oid(value)
        or is_id(value)
        or is_markdown(value)
        or is_unsigned_int(value)
        or is_positive_int(value)
        or is_uuid(value)
    )

is_fhir_primitive_type

is_fhir_primitive_type(value: Any, fhir_type: Type | TypeAliasType | str, raise_on_error: bool = True) -> bool

Check if a value conforms to a FHIR primitive type.

Parameters:

Name Type Description Default
value Any

The value to check

required
fhir_type Type | TypeAliasType | str

The FHIR type to check against (class, TypeAliasType, or string name)

required
raise_on_error bool

Whether to raise FHIRTypeError on unknown type (default: True)

True

Returns:

Name Type Description
bool bool

True if the value conforms to the type, False otherwise

Raises:

Type Description
FHIRTypeError

If the fhir_type is a string and does not correspond to a known type

Examples:

>>> is_fhir_primitive_type("123", primitives.Integer)
True
>>> is_fhir_primitive_type("true", primitives.Boolean)
True
>>> is_fhir_primitive_type("invalid-date", primitives.Date)
False
>>> is_fhir_primitive_type(42, "UnsignedInt")
True
Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_fhir_primitive_type(
    value: Any, fhir_type: Type | TypeAliasType | str, raise_on_error: bool = True
) -> bool:
    """
    Check if a value conforms to a FHIR primitive type.

    Args:
        value: The value to check
        fhir_type: The FHIR type to check against (class, TypeAliasType, or string name)
        raise_on_error: Whether to raise FHIRTypeError on unknown type (default: True)

    Returns:
        bool: `True` if the value conforms to the type, `False` otherwise

    Raises:
        FHIRTypeError: If the fhir_type is a string and does not correspond to a known type

    Examples:
        >>> is_fhir_primitive_type("123", primitives.Integer)
        True
        >>> is_fhir_primitive_type("true", primitives.Boolean)
        True
        >>> is_fhir_primitive_type("invalid-date", primitives.Date)
        False
        >>> is_fhir_primitive_type(42, "UnsignedInt")
        True
    """
    # Handle string type names
    if isinstance(fhir_type, str):
        if hasattr(primitives, fhir_type):
            fhir_type = getattr(primitives, fhir_type)
        else:
            if raise_on_error:
                raise FHIRTypeError(f"Unknown FHIR type: {fhir_type}")
            return False

    # For TypeAliasType, use Pydantic validation
    if not isinstance(fhir_type, TypeAliasType):
        raise FHIRTypeError(f"fhir_type must be a TypeAliasType or string name")

    # Use cached TypeAdapter to avoid recreating it on every call
    type_id = id(fhir_type)
    if type_id not in _type_adapter_cache:
        _type_adapter_cache[type_id] = TypeAdapter(fhir_type)

    try:
        _type_adapter_cache[type_id].validate_python(value)
        return True
    except ValidationError:
        return False

is_fhir_resource_type

is_fhir_resource_type(value: Any, fhir_type: FHIRBaseModel | type | str, raise_on_error: bool = True) -> bool

Check if a value conforms to a FHIR resource.

Parameters:

Name Type Description Default
value Any

The value to check

required
fhir_type FHIRBaseModel | type | str

The complex FHIR type (or name thereof) to check against

required
raise_on_error bool

Whether to raise FHIRTypeError on unknown type (default: True)

True

Returns:

Name Type Description
bool bool

True if the value conforms to the type, False otherwise

Raises:

Type Description
FHIRTypeError

If the fhir_type is a string and does not correspond to a known resource type

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_fhir_resource_type(
    value: Any, fhir_type: "FHIRBaseModel | type | str", raise_on_error: bool = True
) -> bool:
    """
    Check if a value conforms to a FHIR resource.

    Args:
        value: The value to check
        fhir_type: The complex FHIR type (or name thereof) to check against
        raise_on_error: Whether to raise FHIRTypeError on unknown type (default: True)

    Returns:
        bool: `True` if the value conforms to the type, `False` otherwise

    Raises:
        FHIRTypeError: If the fhir_type is a string and does not correspond to a known resource type
    """
    if isinstance(fhir_type, str):
        try:
            resource = get_fhir_resource_type(fhir_type)
        except AttributeError as e:
            if raise_on_error:
                raise e
            else:
                return False
        fhir_type = resource

    try:
        if hasattr(fhir_type, "model_validate"):
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                fhir_type.model_validate(value)  # type: ignore
        return True
    except ValidationError as e:
        return False

is_id

is_id(value: Any) -> bool

Check if value is a valid FHIR Id.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_id(value: Any) -> bool:
    """Check if value is a valid FHIR Id."""
    return is_fhir_primitive_type(value, primitives.Id)

is_instant

is_instant(value: Any) -> bool

Check if value is a valid FHIR Instant.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_instant(value: Any) -> bool:
    """Check if value is a valid FHIR Instant."""
    return (
        is_fhir_primitive_type(value, primitives.Instant)
        if isinstance(value, str)
        else isinstance(value, datetime)
    )

is_integer

is_integer(value: Any) -> bool

Check if value is a valid FHIR Integer.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_integer(value: Any) -> bool:
    """Check if value is a valid FHIR Integer."""
    return is_fhir_primitive_type(value, primitives.Integer)

is_integer64

is_integer64(value: Any) -> bool

Check if value is a valid FHIR Integer64.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_integer64(value: Any) -> bool:
    """Check if value is a valid FHIR Integer64."""
    return is_fhir_primitive_type(value, primitives.Integer64)

is_markdown

is_markdown(value: Any) -> bool

Check if value is a valid FHIR Markdown.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_markdown(value: Any) -> bool:
    """Check if value is a valid FHIR Markdown."""
    return is_fhir_primitive_type(value, primitives.Markdown)

is_oid

is_oid(value: Any) -> bool

Check if value is a valid FHIR Oid.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_oid(value: Any) -> bool:
    """Check if value is a valid FHIR Oid."""
    return is_fhir_primitive_type(value, primitives.Oid)

is_positive_int

is_positive_int(value: Any) -> bool

Check if value is a valid FHIR PositiveInt.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_positive_int(value: Any) -> bool:
    """Check if value is a valid FHIR PositiveInt."""
    return is_fhir_primitive_type(value, primitives.PositiveInt)

is_string

is_string(value: Any) -> bool

Check if value is a valid FHIR String.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_string(value: Any) -> bool:
    """Check if value is a valid FHIR String."""
    return is_fhir_primitive_type(value, primitives.String)

is_time

is_time(value: Any) -> bool

Check if value is a valid FHIR Time.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_time(value: Any) -> bool:
    """Check if value is a valid FHIR Time."""
    return (
        is_fhir_primitive_type(value, primitives.Time)
        if isinstance(value, str)
        else isinstance(value, time)
    )

is_unsigned_int

is_unsigned_int(value: Any) -> bool

Check if value is a valid FHIR UnsignedInt.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_unsigned_int(value: Any) -> bool:
    """Check if value is a valid FHIR UnsignedInt."""
    return is_fhir_primitive_type(value, primitives.UnsignedInt)

is_uri

is_uri(value: Any) -> bool

Check if value is a valid FHIR Uri.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_uri(value: Any) -> bool:
    """Check if value is a valid FHIR Uri."""
    return is_fhir_primitive_type(value, primitives.Uri)

is_url

is_url(value: Any) -> bool

Check if value is a valid FHIR Url.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_url(value: Any) -> bool:
    """Check if value is a valid FHIR Url."""
    return is_fhir_primitive_type(value, primitives.Url)

is_uuid

is_uuid(value: Any) -> bool

Check if value is a valid FHIR Uuid.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def is_uuid(value: Any) -> bool:
    """Check if value is a valid FHIR Uuid."""
    return is_fhir_primitive_type(value, primitives.Uuid)

list_primitive_types

list_primitive_types() -> list[str]

List all available FHIR primitive type names.

Source code in fhircraft/fhir/resources/datatypes/utils.py
def list_primitive_types() -> list[str]:
    """List all available FHIR primitive type names."""
    return [
        name
        for name in dir(primitives)
        if not name.startswith("_")
        and isinstance(getattr(primitives, name), TypeAliasType)
    ]

to_boolean

to_boolean(value: Any) -> Union[bool, None]

Convert value to FHIR Boolean.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[bool, None]

bool or None: Converted boolean value or None if conversion fails

Examples:

>>> to_boolean("true")
True
>>> to_boolean("1")
True
>>> to_boolean("invalid")
None
Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_boolean(value: Any) -> Union[bool, None]:
    """
    Convert value to FHIR Boolean.

    Args:
        value: Value to convert

    Returns:
        bool or None: Converted boolean value or None if conversion fails

    Examples:
        >>> to_boolean("true")
        True
        >>> to_boolean("1")
        True
        >>> to_boolean("invalid")
        None
    """
    if isinstance(value, bool):
        return value
    elif isinstance(value, str):
        lower_val = value.lower()
        if lower_val in ["true", "t", "yes", "y", "1", "1.0"]:
            return True
        elif lower_val in ["false", "f", "no", "n", "0", "0.0"]:
            return False
        else:
            return None
    elif isinstance(value, (int, float)):
        return bool(value)
    else:
        return None

to_date

to_date(value: Any) -> Union[str, None]

Convert value to FHIR Date.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[str, None]

str or None: Converted date string or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_date(value: Any) -> Union[str, None]:
    """
    Convert value to FHIR Date.

    Args:
        value: Value to convert

    Returns:
        str or None: Converted date string or None if conversion fails
    """
    if isinstance(value, str):
        # Check if it's already a valid date
        date_pattern = rf"^{primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?$"
        if re.match(date_pattern, value):
            return value

        # Check if it's a datetime that we can extract date from
        datetime_pattern = rf"^({primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?)(T{primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?)?$"
        datetime_match = re.match(datetime_pattern, value)
        if datetime_match:
            return datetime_match.group(1)  # Extract date part

        return None
    else:
        return None

to_datetime

to_datetime(value: Any) -> Union[str, None]

Convert value to FHIR DateTime.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[str, None]

str or None: Converted datetime string or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_datetime(value: Any) -> Union[str, None]:
    """
    Convert value to FHIR DateTime.

    Args:
        value: Value to convert

    Returns:
        str or None: Converted datetime string or None if conversion fails
    """
    if isinstance(value, str):
        # Check if it's already a valid datetime
        datetime_pattern = rf"^{primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?(T{primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?)?$"
        if re.match(datetime_pattern, value):
            return value

        # Check if it's a date that we can convert to datetime
        date_pattern = rf"^{primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?$"
        if re.match(date_pattern, value):
            return value  # Date is a valid partial datetime

        return None
    else:
        return None

to_decimal

to_decimal(value: Any) -> Union[float, None]

Convert value to FHIR Decimal.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[float, None]

float or None: Converted decimal value or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_decimal(value: Any) -> Union[float, None]:
    """
    Convert value to FHIR Decimal.

    Args:
        value: Value to convert

    Returns:
        float or None: Converted decimal value or None if conversion fails
    """
    if isinstance(value, (int, float)):
        return float(value)
    elif isinstance(value, bool):
        return float(value)
    elif isinstance(value, str):
        try:
            # Check if it matches decimal pattern
            if re.match(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$", value.strip()):
                return float(value)
            else:
                return None
        except ValueError:
            return None
    else:
        return None

to_integer

to_integer(value: Any) -> Union[int, None]

Convert value to FHIR Integer.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[int, None]

int or None: Converted integer value or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_integer(value: Any) -> Union[int, None]:
    """
    Convert value to FHIR Integer.

    Args:
        value: Value to convert

    Returns:
        int or None: Converted integer value or None if conversion fails
    """
    if isinstance(value, int):
        return value
    elif isinstance(value, bool):
        return int(value)
    elif isinstance(value, str):
        if re.match(r"^[+-]?\d+$", value.strip()):
            try:
                return int(value)
            except ValueError:
                return None
        else:
            return None
    else:
        return None

to_quantity

to_quantity(value: Any) -> Union[Any, None]

Convert value to FHIR Quantity.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[Any, None]

Quantity or None: Converted Quantity object or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_quantity(value: Any) -> Union[Any, None]:
    """
    Convert value to FHIR Quantity.

    Args:
        value: Value to convert

    Returns:
        Quantity or None: Converted Quantity object or None if conversion fails
    """
    try:
        # Import here to avoid circular imports
        Quantity = get_complex_FHIR_type("Quantity")

        if isinstance(value, str):
            # Try to parse "value unit" format like "10.5 mg"
            quantity_match = re.match(r"^(\d+(?:\.\d+)?)\s*([a-zA-Z]+)$", value.strip())
            if quantity_match:
                val, unit = quantity_match.groups()
                decimal_val = to_decimal(val)
                if decimal_val is not None:
                    return Quantity(value=decimal_val, unit=unit)  # type: ignore
            return None
        elif isinstance(value, (int, float)):
            # Simple numeric value becomes quantity with unit "1"
            return Quantity(value=float(value), unit="1")  # type: ignore
        elif isinstance(value, bool):
            # Boolean to quantity: True=1.0, False=0.0
            return Quantity(value=float(value), unit="1")  # type: ignore
        else:
            return None
    except Exception:
        return None

to_string

to_string(value: Any) -> Union[str, None]

Convert value to string representation.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[str, None]

str or None: String representation or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_string(value: Any) -> Union[str, None]:
    """
    Convert value to string representation.

    Args:
        value: Value to convert

    Returns:
        str or None: String representation or None if conversion fails
    """
    if isinstance(value, str):
        return value
    elif isinstance(value, (int, float, bool)):
        return str(value)
    elif hasattr(value, "__str__"):
        try:
            return str(value)
        except Exception:
            return None
    else:
        return None

to_time

to_time(value: Any) -> Union[str, None]

Convert value to FHIR Time.

Parameters:

Name Type Description Default
value Any

Value to convert

required

Returns:

Type Description
Union[str, None]

str or None: Converted time string or None if conversion fails

Source code in fhircraft/fhir/resources/datatypes/utils.py
def to_time(value: Any) -> Union[str, None]:
    """
    Convert value to FHIR Time.

    Args:
        value: Value to convert

    Returns:
        str or None: Converted time string or None if conversion fails
    """
    if isinstance(value, str):
        # Check if it's already a valid time
        time_pattern = rf"^{primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?$"
        if re.match(time_pattern, value):
            return value

        # Check if it's a datetime/date that contains time info we can extract
        datetime_pattern = rf"^({primitives.YEAR_REGEX}(-{primitives.MONTH_REGEX}(-{primitives.DAY_REGEX})?)?)(T({primitives.HOUR_REGEX}(:{primitives.MINUTES_REGEX}(:{primitives.SECONDS_REGEX}({primitives.TIMEZONE_REGEX})?)?)?))$"
        datetime_match = re.match(datetime_pattern, value)
        if datetime_match:
            return datetime_match.group(4)  # Extract time part

        return None
    else:
        return None