2

I have a function that uses typing.get_type_hints. I want to add a documentation test to it. However, it looks like get_type_hints fails to resolve types that are defined in a doctest.

Here is a simplified example:

import typing

def f(clazz):
    """
    >>> class MyClass:
    ...   my_field: 'MyClass'
    >>> f(MyClass)
    """
    typing.get_type_hints(clazz)

When running it with python3 -m doctest test.py it throws NameError: name 'MyClass' is not defined.

lovasoa
  • 6,419
  • 1
  • 35
  • 45

2 Answers2

2

In order to get it to work in doctest, you would need to provide the correct evaluation scope.

Try this:

import typing

def f(clazz, globalns=None, localns=None):
    """
    >>> class MyClass:
    ...   my_field: 'MyClass'
    >>> f(MyClass, globals(), locals())
    """
    typing.get_type_hints(clazz, globalns, localns)

In doctest, a special set of values are used in the "eval scope" that happens with get_typing_hints. It is looking for "test.MyClass" which doesn't actually exist otherwise.

Alphadelta14
  • 2,854
  • 3
  • 16
  • 19
1
from __future__ import annotations

import typing


def f(clazz):
    """
    >>> test = 1
    >>> class MyClass:
    ...   my_field:'MyClass'
    >>> f(MyClass)
    """
    typing.get_type_hints(clazz)

add from __future__ import annotations at the beginning of the file, it work for me on python3.7

QIFENG LI
  • 111
  • 3
  • It works, indeed. Thank you ! Is this a bug in the typing module ? – lovasoa May 01 '19 at 15:26
  • I also still wonder why `my_field:'MyClass'` not work when it in doctest, it has different behavior when it in doctest and not. It seem the new syntax not yet ready when it in doctest. – QIFENG LI May 01 '19 at 15:40
  • Unfortunately, it seems that the problem also exists with PEP563 annotations: https://gist.github.com/lovasoa/74ea62a89f5bf073b0e0c2f222008ae3 – lovasoa May 06 '19 at 07:36