ahvn.utils.basic.type_utils module

ahvn.utils.basic.type_utils.autotype(obj)[source]

Automatically convert a string to its appropriate Python type.

Tries to parse the string as different types in order of precedence: integer → float → boolean → None → JSON → JSON lines → Python expression → string

This is useful for parsing configuration values, command line arguments, or user input where the type should be inferred from the string format.

Warning: evaluates Python expressions using eval(), which can be dangerous. Use with caution and only with controlled input sources.

Parameters:

obj (str) – The string to convert to an appropriate type.

Return type:

Any

Returns:

The converted object. If no conversion is possible, returns the original string.

Examples

>>> autotype("42")
42
>>> type(autotype("42"))
<class 'int'>
>>> autotype("3.14")
3.14
>>> type(autotype("3.14"))
<class 'float'>
>>> autotype("true")
True
>>> autotype("false")
False
>>> autotype("none")
None
>>> autotype("null")
None
>>> autotype("'hello'")  # Quoted strings remain as strings
'hello'
>>> autotype('"world"')
'world'
>>> autotype('{"key": "value"}')  # JSON parsing
{'key': 'value'}
>>> autotype("[1, 2, 3]")
[1, 2, 3]
>>> autotype("1 + 2")  # Expression evaluation
3
>>> autotype("Hello, World!")  # Fallback to string
'Hello, World!'

Warning

Uses eval() for expression evaluation, which can be dangerous with untrusted input. Use with caution and only with controlled input sources.

ahvn.utils.basic.type_utils.jsonschema_type(type_annotation)[source]

Convert a Python type annotation string to JSON schema format.

This is the main function for converting Python type annotations to JSON schemas. It handles complex types including generics, unions, literals, and optional types.

Parameters:

type_annotation (Optional[str]) – A Python type annotation string (e.g., “int”, “List[str]”, “Optional[Dict[str, int]]”, “Literal[‘fast’, ‘slow’]”).

Returns:

>>> jsonschema_type("int")
{'type': 'integer'}
>>> jsonschema_type("List[str]")
{'type': 'array', 'items': {'type': 'string'}}
>>> jsonschema_type("Optional[str]")
{'type': 'string'}
>>> jsonschema_type("Union[str, int]")
{'type': 'string', 'x-original-union': ['str', 'int']}
>>> jsonschema_type("Literal['fast', 'slow']")
{'type': 'string', 'enum': ['fast', 'slow']}
>>> jsonschema_type("datetime")
{'type': 'string', 'format': 'date-time'}
>>> jsonschema_type("CustomType")
{'type': 'string', 'x-original-type': 'CustomType'}
>>> jsonschema_type("")
{}

Return type:

A JSON schema dictionary. Examples

Note

Unknown or complex types are typically converted to {‘type’: ‘string’} with additional metadata stored in x-original-* fields for debugging.

ahvn.utils.basic.type_utils.parse_function_signature(func)[source]

Extract type information and defaults from a Python function signature.

This function analyzes a function’s signature and docstring to extract comprehensive type information, default values, and parameter metadata. It combines signature inspection with docstring parsing for complete information.

Parameters:

func (callable) – The Python function to analyze.

Returns:

>>> def example_func(a: int, b: str = "default", c: Optional[float] = None) -> bool:
...     '''Example function.
...
...     Args:
...         a (int): First parameter.
...         b (str, optional): Second parameter. Defaults to "default".
...         c (Optional[float], optional): Third parameter. Defaults to None.
...     '''
...     return True
>>>
>>> result = parse_function_signature(example_func)
>>> result['parameters']['a']['type']
'integer'
>>> result['parameters']['a']['required']
True
>>> result['parameters']['b']['type']
'string'
>>> result['parameters']['b']['default']
'default'
>>> result['parameters']['b']['required']
False
>>> result['return_type']
{'type': 'boolean'}

Return type:

A dictionary containing parameter information with the following structure

The returned dictionary has these keys:
  • ‘parameters’: Dict mapping parameter names to their schema info

  • ‘return_type’: JSON schema for the return type

  • ‘has_var_args’: Boolean indicating if *args present

  • ‘has_var_kwargs’: Boolean indicating if **kwargs present

Note

This only analyzes the function signature - for full docstring parsing including descriptions, use parse_docstring() from func_utils.