extended_data.primitives.types¶
Type Utilities.
This module provides utility functions related to Python types, specifically for retrieving default values based on the type, converting special types to simpler forms, and reconstructing simplified types back to their original forms. It includes functions for getting default values for common types, determining whether to return primitive or exact types of a given value, and handling conversions for datetime, path, and complex types.
Functions: - get_default_value_for_type: Returns the default value for a given type. - get_primitive_type_for_instance_type: Returns the primitive type for a given value. - typeof: Returns the type (or primitive type) of a given value. - convert_special_type: Converts a single special type to a simpler form. - convert_special_types: Converts an object and its contents to simpler forms. - reconstruct_special_type: Reconstructs a simplified type back to its original form. - reconstruct_special_types: Reconstructs an object and its contents back to their original types.
Classes: - ConversionError: Custom error class for handling conversion failures. - ReconstructionError: Custom error class for handling reconstruction failures.
Constants: - DATE_PATTERN: Regex for matching ISO 8601 date strings. - DATETIME_PATTERN: Regex for matching ISO 8601 datetime strings. - TIME_PATTERN: Regex for matching time strings. - PATH_PATTERN: Regex for matching Unix and Windows-style paths. - INTEGER_PATTERN: Regex for matching integer strings. - NUMBER_PATTERN: Regex for matching numeric strings. - TRUTHY_PATTERN: Regex for matching truthy strings. - FALSY_PATTERN: Regex for matching falsy strings.
Module Contents¶
Functions¶
Converts a string representation of truth to boolean. |
|
Converts a string representation of a float to a float. |
|
Converts a string representation of an integer to an int. |
|
Converts a string or byte representation of a path to a pathlib.Path object. |
|
Converts a string representation of a date to a datetime.date object. |
|
Converts a string representation of a datetime to a datetime.datetime object. |
|
Converts a string representation of a time to a datetime.time object. |
|
Returns the default value for a given type. |
|
Gets the primitive type for a given value. |
|
Determines either the primitive or exact type of a given value. |
|
Converts a single special type to a simpler form. |
|
Converts an object and its contained objects of special types to simpler forms. |
|
Check if the given string is a potential YAML document. |
|
Check if the given string is a potential JSON object or array. |
|
Attempts to reconstruct a special type from a string representation by sequentially matching known patterns and decoding them. |
|
Recursively reconstructs special types within nested data structures. |
|
Convert an object to a hashable type for use in cache keys or sets. |
Data¶
API¶
- extended_data.primitives.types.DATE_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.DATETIME_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.TIME_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.PATH_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.INTEGER_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.NUMBER_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.TRUTHY_PATTERN: re.Pattern[str] = 'compile(...)'¶
- extended_data.primitives.types.FALSY_PATTERN: re.Pattern[str] = 'compile(...)'¶
- exception extended_data.primitives.types.ConversionError(expected_type: type[Any], value: Any)¶
Bases:
ValueErrorCustom error class for handling conversion failures.
This error is raised during type conversions when the input value does not conform to the expected type format. For Path types, it ensures consistent error messaging across Python versions by normalizing the type representation.
Args: expected_type (type): The expected Python type. value (Any): The actual value being converted.
Raises: ValueError: Always raises as this is an error class.
Example: >>> raise ConversionError(int, ‘invalid’) ConversionError: Invalid <class ‘int’> value: ‘invalid’ >>> raise ConversionError(Path, ‘invalid:://path’) ConversionError: Invalid <class ‘pathlib.Path’> value: ‘invalid:://path’ >>> raise ConversionError(float, ‘not_a_number’) ConversionError: Invalid <class ‘float’> value: ‘not_a_number’
Note: When the expected_type is pathlib.Path, the error message will consistently display as “<class ‘pathlib.Path’>” regardless of the internal Path implementation in different Python versions.
Initialization
Initialize the ConversionError with expected type and value.
Args: expected_type (type): The expected Python type. Special handling is applied for pathlib.Path to ensure consistent error messages across Python versions. value (Any): The actual value that failed conversion. Will be represented using repr() in the error message.
Note: For Path types, the error message will always use ‘pathlib.Path’ notation regardless of the internal implementation details of the Path class in different Python versions.
- extended_data.primitives.types.string_to_bool(val: str | bool | None, raise_on_error: bool = False) bool | None¶
Converts a string representation of truth to boolean.
Args: val (str | bool | None): The value to convert. raise_on_error (bool): Whether to raise an error on invalid value. Defaults to False.
Returns: bool | None: The converted boolean value, or None if invalid and raise_on_error is False.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.string_to_float(val: str, raise_on_error: bool = False) float | None¶
Converts a string representation of a float to a float.
Args: val (str): The string value to convert. raise_on_error (bool): Whether to raise an error on invalid value. Defaults to False.
Returns: float | None: The converted float value, or None if invalid and raise_on_error is False.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.string_to_int(val: str, raise_on_error: bool = False) int | None¶
Converts a string representation of an integer to an int.
Args: val (str): The string value to convert. raise_on_error (bool): Whether to raise an error on invalid value. Defaults to False.
Returns: int | None: The converted integer value, or None if invalid and raise_on_error is False.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.string_to_path(val: str | bytes | os.PathLike[str] | None, raise_on_error: bool = False) pathlib.Path | None¶
Converts a string or byte representation of a path to a pathlib.Path object.
Args: val (str | bytes | pathlib.Path | None): The value to convert. raise_on_error (bool): Whether to raise an error on invalid value. Defaults to False.
Returns: pathlib.Path | None: The converted Path object, or None if invalid and raise_on_error is False.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.string_to_date(val: str, raise_on_error: bool = False) datetime.date | None¶
Converts a string representation of a date to a datetime.date object.
Args: val (str): The string to convert, expected to be in the format YYYY-MM-DD. raise_on_error (bool): Whether to raise an error on invalid format. Defaults to False.
Returns: datetime.date | None: The converted date object, or None if the format is invalid.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.string_to_datetime(val: str, raise_on_error: bool = False) datetime.datetime | None¶
Converts a string representation of a datetime to a datetime.datetime object.
Args: val (str): The string to convert, expected to match various datetime formats like YYYY-MM-DDTHH:MM[:SS][.fff][Z|±hh:mm]. raise_on_error (bool): Whether to raise an error on invalid format. Defaults to False.
Returns: datetime.datetime | None: The converted datetime object, or None if the format is invalid.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.string_to_time(val: str, raise_on_error: bool = False) datetime.time | None¶
Converts a string representation of a time to a datetime.time object.
Args: val (str): The string to convert, expected to be in the format HH:MM[:SS] or HH:MM:SS.ffffff. raise_on_error (bool): Whether to raise an error on invalid format. Defaults to False.
Returns: datetime.time | None: The converted time object, or None if the format is invalid.
Raises: ConversionError: If the value is invalid and raise_on_error is True.
- extended_data.primitives.types.get_default_value_for_type(input_type: type[Any]) Any¶
Returns the default value for a given type.
- extended_data.primitives.types.get_primitive_type_for_instance_type(value: Any) type[Any]¶
Gets the primitive type for a given value.
- extended_data.primitives.types.typeof(item: Any, primitive_only: bool = False) type[Any]¶
Determines either the primitive or exact type of a given value.
- extended_data.primitives.types.convert_special_type(obj: Any) Any¶
Converts a single special type to a simpler form.
- extended_data.primitives.types.convert_special_types(obj: Any) Any¶
Converts an object and its contained objects of special types to simpler forms.
- extended_data.primitives.types.is_potential_yaml(obj: str) bool¶
Check if the given string is a potential YAML document.
:param obj: The string to be checked. :return: True if the string is a potential YAML document, False otherwise.
- extended_data.primitives.types.is_potential_json(obj: str) bool¶
Check if the given string is a potential JSON object or array.
:param obj: The string to be checked. :return: True if the string is a potential JSON object or array, False otherwise.
- extended_data.primitives.types.reconstruct_special_type(converted_obj: str, fail_silently: bool = False) Any¶
Attempts to reconstruct a special type from a string representation by sequentially matching known patterns and decoding them.
Args: converted_obj (str): The string representation of the object to reconstruct. fail_silently (bool): Whether to fail silently without raising errors. Defaults to False.
Returns: Any: The reconstructed object or the original string if reconstruction fails.
Raises: ConversionError: If reconstruction fails and fail_silently is False.
- extended_data.primitives.types.reconstruct_special_types(obj: Any, fail_silently: bool = False) Any¶
Recursively reconstructs special types within nested data structures.
Args: obj (Any): The object to reconstruct. fail_silently (bool): Whether to fail silently without raising errors. Defaults to False.
Returns: Any: The reconstructed object with special types restored where applicable.
- extended_data.primitives.types.make_hashable(obj: Any, _memo: set[int] | None = None) Any¶
Convert an object to a hashable type for use in cache keys or sets.
This function recursively converts mutable types (dicts, lists) to their immutable equivalents (frozensets of tuples, tuples) so they can be used as dictionary keys or in sets.
Args: obj: The object to convert to a hashable type.
Returns: A hashable representation of the object: - Primitives (str, int, float, bool, None) are returned as-is - Lists and tuples are converted to tuples of hashable items - Dicts are converted to frozensets of (key, value) tuples - Other types are converted to their string representation
Examples: >>> make_hashable({“a”: 1, “b”: [2, 3]}) frozenset({(‘a’, 1), (‘b’, (2, 3))}) >>> make_hashable([1, 2, {“x”: “y”}]) (1, 2, frozenset({(‘x’, ‘y’)}))