How to type hint a function that returns a NamedTuple that has been created within the function

Viewed 800

My IDE's (PyCharm) linter indicates that I'm making a mistake with my return type-hinting when creating a namedtuple within a function. The problem appears to be that I'm saying that I will return type NamedTuple when actually I'm returning type MyNamedTuple. How can I solve this?

Example:

from typing import Dict, NamedTuple

def foo(bar: Dict) -> NamedTuple:
    MyNamedTuple = NamedTuple("MyNamedTuple", [(k, int) for k in bar.keys()])
    d = {k: v for k, v in bar.items()}
    return MyNamedTuple(**d)

>>> foo({"a": 1, "b": 2})
MyNamedTuple(a=1, b=2)

0 Answers
Related