I would like to implement a function that returns a new type. And the returned type should be compatible with static type checkers. The initial idea I had was for the function to have a -> type
return. However, this does not work because type checkers consider the assigned value to be a variable. The following code snippet illustrates it:
def create_custom_type(name: str, **kwargs) -> type:
# Here logic that creates custom_type
return custom_type
my_type = create_custom_type("my_type", ...)
def my_function(
arg: my_type # this gives type error, but want it to be okay!
):
pass
my_var = my_type("some value")
my_function(my_var) # want this to be okay!
my_function(0) # want to get here unexpected argument error!
Is there currently way to implement a function that creates types compatible with static type checking? If there isn’t, would there be the possibility to add this to the typing system?
One idea could be that the function have a return type as -> NewType
. This way static type checkers know that the assignment of the return of the function should be considered a new type, and not a variable.