mypythontools.types package¶
Module with some helpers for type hints and annotations.
- mypythontools.types.get_return_type_hints(func: Callable) Any [source]¶
Return function return types. .. note:
This is not working on older versions that 3.9. It will not raise, but return None. If you need it on 3.7, you can use `get_return_type_hints_evaluated`.
- Parameters
func (Callable) – Function with type hints.
- Returns
Type of return. E.g. <class ‘tuple’> or typing_extensions.Literal[‘int’, ‘float’].
- Return type
Any
Example
>>> # You can use Union as well as Literal >>> def union_return() -> int | float: ... return 1 >>> inferred_type = get_return_type_hints(union_return) >>> 'int' in str(inferred_type) and 'float' in str(inferred_type) True >>> def literal_return() -> Literal[1, 2, 3]: ... return 1 >>> inferred_type = get_return_type_hints(literal_return) >>> 'Literal' in str(inferred_type) True
- mypythontools.types.json_to_py(json: dict, replace_comma_decimal: bool = True, replace_true_false: bool = True) Any [source]¶
Take json and eval it from strings. If string to string, if float to float, if object then to dict.
When to use? - If sending object as parameter in function.
- Parameters
json (dict) – JSON with various formats as string.
replace_comma_decimal (bool, optional) – Some countries use comma as decimal separator (e.g. 12,3). If True, comma replaced with dot (Only if there are no brackets (list, dict…) and if not converted to number string remain untouched) . For example ‘2,6’ convert to 2.6. Defaults to True
replace_true_false (bool, optional) – If string is ‘false’ or ‘true’ (for example from javascript), it will be capitalized first for correct type conversion. Defaults to True
- Returns
Python dictionary with correct types.
- Return type
dict
Example
>>> # Can be beneficial for example when communicating with JavaScript >>> json_to_py({'one_two': '1,2'}) {'one_two': 1.2}
- mypythontools.types.small_validate(value, allowed_type: None | Any = None, name: str | None = None) None [source]¶
Type validation. It also works for Union and validate Literal values.
Instead of typeguard validation, it define just subset of types, but is simplier and needs no extra import, therefore can be faster.
- Parameters
value (Any) – Value that will be validated.
allowed_type (Any, optional) – For example int, str or list. It can be also Union or Literal. If Literal, validated value has to be one of Literal values. If None, it’s skipped. Defaults to None.
name (str | None, optional) – If error raised, name will be printed. Defaults to None.
- Raises
TypeError – Type does not fit.
Examples
>>> from typing_extensions import Literal ... >>> small_validate(1, int) >>> small_validate(None, Union[list, None]) >>> small_validate("two", Literal["one", "two"]) >>> small_validate("three", Literal["one", "two"]) Traceback (most recent call last): ValidationError: ...
- mypythontools.types.str_to_bool(bool_str)[source]¶
Convert string to bool. Usually used from argparse. Raise error if don’t know what value.
Possible values for True: ‘yes’, ‘true’, ‘t’, ‘y’, ‘1’ Possible values for False: ‘no’, ‘false’, ‘f’, ‘n’, ‘0’
- Parameters
bool_str (str) –
- Raises
TypeError – If not one of bool values inferred, error is raised.
- Returns
True or False
- Return type
bool
Example
>>> str_to_bool("y") True
Argparse example:
parser = argparse.ArgumentParser() parser.add_argument( "--test", choices=(True, False), type=str_to_bool, nargs="?", )
- mypythontools.types.str_to_infer_type(string_var: str) Any [source]¶
Convert string to another type (for example to int, float, list or dict).
- Parameters
string_var (str) – String that should be converted.
- Returns
New inferred type.
- Return type
Any
Examples
>>> type(str_to_infer_type("1")) <class 'int'> >>> type(str_to_infer_type("1.2")) <class 'float'> >>> type(str_to_infer_type("['one']")) <class 'list'> >>> type(str_to_infer_type("{'one': 1}")) <class 'dict'>
- mypythontools.types.typechecked_compatible(function)[source]¶
Turns off type checking for old incompatible python versions.
Mainly for new syntax like list[str] which raise TypeError.
- mypythontools.types.validate_sequence(value, variable)[source]¶
Ensure, that defined sequence is not just a string.
Usually with Sequence we means for example tuple or list of items. String in some cases is not valid type then. This ensure, that this is Sequence, but not just string.
- Parameters
value (Sequence) – Variable where we want to ensure Sequence type.
variable (_type_) – If it is just string, this will raise an error with name of variable with incorrect type.
- Raises
TypeError – If it is just a string.