I started implementing Type Hinting in a large code base worked on by multiple developers to increase transparency on what functions should expect as arguments.
What I would like to do is also validate that the arguments being passed to the function are the correct types.
This would be easy to do inside the function, but that doesn't seem pythonic. I want to make a utility that can be passed the args and types from the function and raises an exception if an incorrect type is passed for the corresponding arg.
example:
def find_integer_sum(a: int, b: int):
utility.validate_args(args, types)
return a + b
What I want is to somehow pass the args and types to a function without needing to always manually insert utility.validate_args({a: int, b: int})
as that can get cumbersome.
Is there a way to access args with their type hints?
Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types. As the name says, type hints just suggest types.
Python's type hints provide you with optional static typing to leverage the best of both static and dynamic typing. Besides the str type, you can use other built-in types such as int , float , bool , and bytes for type hintings. To check the syntax for type hints, you need to use a static type checker tool.
It is a type variable. Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions.
“Mypy is an optional static type checker for Python that aims to combine the benefits of dynamic (or 'duck') typing and static typing. Mypy combines the expressive power and convenience of Python with a powerful type system and compile-time type checking.” A little background on the Mypy project.
From the Python typing
documentation, you may use typing.get_type_hints()
.
typing.get_type_hints(obj[, globals[, locals]])
Return a dictionary containing type hints for a function, method, module or class object.This is often the same as
obj.__annotations__
. In addition, forward references encoded as string literals are handled by evaluating them inglobals
andlocals
namespaces. If necessary,Optional[t]
is added for function and method annotations if a default value equal toNone
is set. For a classC
, return a dictionary constructed by merging all the__annotations__
alongC.__mro__
in reverse order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With