Avoiding the use of Any #1246
Replies: 6 comments 2 replies
-
sometimes to avoid union returns you can use overloads maybe something like this from typing import Any, cast, overload
@overload
def validate_list(this_object: list) -> list: ...
def validate_list(this_object: Any) -> Any:
if isinstance(this_object, list):
print('this_object is a list ... hooray')
return this_object
else:
print('this_object is not a list ... grimbo :(')
dodgy_object: Any = cast(Any, this_object)
return dodgy_object |
Beta Was this translation helpful? Give feedback.
-
Will look into @overload. But, the code is still using Any ? |
Beta Was this translation helpful? Give feedback.
-
true, but it will help typecheckers when accessing the return type if you are passing in a known list |
Beta Was this translation helpful? Give feedback.
-
How are you planning to use this validation function? Maybe a |
Beta Was this translation helpful? Give feedback.
-
I've built an api where the inputs are different types of objects including lists of strings. The validation functions ensure the input is correct. If possible, I'd like to avoid the use of Any. The other reason to eliminate the use of Any is because the plan is to test the code base with mypyc. The mypyc documentation discourages the use of Any. |
Beta Was this translation helpful? Give feedback.
-
Re: What do you intend for the validation function to do at runtime when it detects that the object doesn't match the validation criteria?
Thank-you for the code and will try it out. |
Beta Was this translation helpful? Give feedback.
-
This is a function to validate incoming objects as lists of strings:
For brevity, the code is not checking if this_object contains strings.
If this_object is not a list then it is cast as Any to match the function's return type.
If this_object is a list then it is also returned as an Any object.
If allowed, I could use Union[Any, list[str]] as the return type. If so, isn't Union[Any] the same as Union[Any, list[str]]?
Finally, how do you avoid the use of Any in this case? Thanks
Beta Was this translation helpful? Give feedback.
All reactions