Skip to content

get_type_hints() fails on Mark.__init__ #3635

@Vlad-Shcherbina

Description

@Vlad-Shcherbina

To reproduce, run the following snippet:

import typing
import _pytest.mark
print(typing.get_type_hints(_pytest.mark.Mark.__init__))

Expected:

{'return': <class 'NoneType'>, 'name': <class 'str'>, 'args': typing.List[object], 'kwargs': typing.Dict[str, object]}

Actual:

Traceback (most recent call last):
  File ".\example.py", line 3, in <module>
    print(typing.get_type_hints(_pytest.mark.Mark.__init__))
  File "C:\Python37\lib\typing.py", line 1001, in get_type_hints
    value = _eval_type(value, globalns, localns)
  File "C:\Python37\lib\typing.py", line 260, in _eval_type
    return t._evaluate(globalns, localns)
  File "C:\Python37\lib\typing.py", line 464, in _evaluate
    eval(self.__forward_code__, globalns, localns),
  File "<string>", line 1, in <module>
NameError: name 'List' is not defined

This happens because of these type annotations:

@attr.s(frozen=True)
class Mark(object):
#: name of the mark
name = attr.ib(type=str)
#: positional arguments of the mark decorator
args = attr.ib(type="List[object]")
#: keyword arguments of the mark decorator
kwargs = attr.ib(type="Dict[str, object]")

It's probably a minor issue that has no effect on the normal operation of pytest, but it could trip up runtime annotation analysis tools.

If the codebase was Python 3 only, the fix would be trivial:

from typing import List, Dict
...
@attr.s(frozen=True)
class Mark(object):
    name = attr.ib(type=str)
    args = attr.ib(type=List[object])
    kwargs = attr.ib(type=Dict[str, object])

But I'm not sure how to proceed in Python 2/3 codebase, adding the conditionals does not seem justified for such a tiny thing.


Version info:

  • Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
  • pytest 3.6.2 or pytest 3.6.3.dev33+ga48c47b5

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: enhancementnew feature or API change, should be merged into features branch

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions