3

Type hint can define the return type in Python, so when a function returns namedtuple type, then how to define it?

def bar(func):
    def decorator(*args, **kwargs):
        return namedtuple('data', 'name user')(**func(*args, **kwargs))

    return update_wrapper(decorator, func)


@bar
def info() -> NamedTuple:
    return {'name': 'a1', 'user': 'b1'}

Expected type 'NamedTuple', got Dict[str,str] instead

As you know, the function info() returns Dict[str, str], but the decorator @bar changes it. Now the function info() returns a namedtuple object, so is there a way to indicate that the function info() returns a namedtupe object by type hint?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
robin.xu
  • 31
  • 1
  • 4
  • Do you know how to use namedtuples? And have you read the docs for [`typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple) – Jab Jun 04 '19 at 04:43
  • Welcome to SO. I assume you get the error on the `info` method? – Bernhard Jun 04 '19 at 04:44
  • Does this answer your question? [Type hints in namedtuple](https://stackoverflow.com/questions/34269772/type-hints-in-namedtuple) – mkrieger1 Feb 01 '23 at 10:19

1 Answers1

1

NamedTuple instances are created via collections.namedtuple() function.

Since you are interested in typing elements of namedtuple, you could create a custom type that inherits the typed version of NamedType (as mentioned by @jab) and use it in type hints as shown below.

from typing import NamedTuple

class CustomType(NamedTuple):
    name: str
    user: str

def info() -> CustomType:
    return CustomType('a1', 'b1')
  • 1
    This is an informative answer, but the code shown doesn't match the context of the question. How does the decorator (`@bar`) fit into this... I'd like to know. – TrebledJ Jun 04 '19 at 05:06
  • 1
    In the question, the error message corresponds to the type hint of `info()`. I assumed `@bar` is part of OP's attempt to add type hint to `info()`. If the assumption is correct, then `@bar` is not required. If not, then OP should clarify the intended purpose of `@bar`. – Venkatesh-Prasad Ranganath Jun 04 '19 at 05:14