robin.xu
robin.xu

Reputation: 41

How to type hint namedtuple in Python?

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?

Upvotes: 4

Views: 6438

Answers (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')

Upvotes: 1

Related Questions