ahvn.utils.basic.type_utils module¶
- ahvn.utils.basic.type_utils.autotype(obj)[源代码]¶
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.
- 参数:
obj (
str) -- The string to convert to an appropriate type.- 返回类型:
- 返回:
The converted object. If no conversion is possible, returns the original string.
示例
>>> 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!'
警告
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)[源代码]¶
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.
- 参数:
type_annotation (
Optional[str]) -- A Python type annotation string (e.g., "int", "List[str]", "Optional[Dict[str, int]]", "Literal['fast', 'slow']").- 返回:
>>> 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("") {}
- 返回类型:
A JSON schema dictionary. Examples
备注
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)[源代码]¶
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.
- 参数:
func (
callable) -- The Python function to analyze.- 返回:
>>> 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'}
- 返回类型:
A dictionary containing parameter information with the following structure
- The returned dictionary has these keys:
备注
This only analyzes the function signature - for full docstring parsing including descriptions, use parse_docstring() from func_utils.