Issue
I am committed to using type annotations but I want to compare types, one a fundamental type and one an Optional[..] wrapped type. I think I need to look 'through' the Optional[ ... ] type hint modifier. This is in Python 3.10.
My code example is below. I want to get the message "Yes they both can contain strings".
Is there a call I use to replace type( my_optional_string ) that returns the underlying str type within?
from typing import Optional
my_string : str = ""
my_optional_string : Optional[str] = ""
if type(my_string) == type( my_optional_string ):
print("Yes they both can contain strings")
else:
print("No, not stringy types")
Solution
I'm afraid there is no a universal and straightforward solution, but the result you want can be achieved using typing introspection functions. In this case to obtain variable annotations we are forced to use their names in text form.
Like so:
import sys
from typing import Optional, get_type_hints, get_args, get_origin, Union
def can_be_str(type_: type) -> bool:
return type_ is str or (get_origin(type_) is Union and str in get_args(type_))
my_string: str = ""
my_optional_string: Optional[str] = None
my_int: int = 1
my_optional_int: Optional[int] = None
# get annotations for current module
type_hints = get_type_hints(sys.modules[__name__])
assert can_be_str(type_hints["my_string"]) is True
assert can_be_str(type_hints["my_optional_string"]) is True
assert can_be_str(type_hints["my_int"]) is False
assert can_be_str(type_hints["my_optional_int"]) is False
Answered By - alex_noname Answer Checked By - Mary Flores (Python.Easybugfix Volunteer)
Post a Comment
Post a Comment