typing_inspect
typing_inspect copied to clipboard
is_forward_ref() and eval_forward_ref(globs, locs)
Not sure these need to be in typing_inspect, but for I am currently relying on the private names so I guess there is maybe something to do in the api here?
def is_forward_ref(typ):
"""
Returns true if typ is a typing ForwardRef
:param typ:
:return:
"""
return isinstance(typ, _ForwardRef)
class InvalidForwardRefError(Exception):
""" Raised whenever some forward reference can not be evaluated """
def __init__(self, invalid: _ForwardRef):
self.invalid_ref = invalid
def __str__(self):
return "Invalid PEP484 type hint: forward reference {} could not be resolved with the current stack's " \
"variables".format(self.invalid_ref)
def eval_forward_ref(typ: _ForwardRef):
"""
Climbs the current stack until the given Forward reference has been resolved, or raises an InvalidForwardRefError.
:param typ: the forward reference to resolve
:return:
"""
for frame in stack():
try:
return typ._eval_type(frame[0].f_globals, frame[0].f_locals)
except NameError:
pass
raise InvalidForwardRefError(typ)
As always if this is too high-level / specific, feel, free to suggest to move it to pytypes or equivalent libs.
For example the eval_forward_ref above could be replaced with the low-level
def eval_forward_ref(typ, globs, locs):
return typ._eval_type(globs, locs)
I like the is_forward_ref. But for eval_forward_ref I think we should use more of typing logic used in get_type_hints, i.e. support custom locals and globals.
@ilevkivskyi @smarie is there any news on this? I'll be hardcoding is_forward_ref function to my lib to work with this but it would be great to have them at typing_inspect :)
@allrod5
I think adding is_forward_ref() totally makes sense (it needs to also account the renaming of _ForwardRef to ForwardRef in newer Python versions). I recently needed it myself actually. Would you like to make a PR?
I surely can, will do it soon :)
@ilevkivskyi submitted: https://github.com/ilevkivskyi/typing_inspect/pull/57
Could you release the latest version of the library with forward_ref support?
OK, I will make a release soon.
I just uploaded new version to PyPI: https://pypi.org/project/typing-inspect/0.6.0/
Thanks!