question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

is_forward_ref() and eval_forward_ref(globs, locs)

See original GitHub issue

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)

Issue Analytics

  • State:open
  • Created 6 years ago
  • Reactions:1
  • Comments:9 (7 by maintainers)

github_iconTop GitHub Comments

3reactions
ilevkivskyicommented, May 2, 2020

I just uploaded new version to PyPI: https://pypi.org/project/typing-inspect/0.6.0/

1reaction
andreycizovcommented, May 1, 2020

Could you release the latest version of the library with forward_ref support?

Read more comments on GitHub >

github_iconTop Results From Across the Web

No results found

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found