Search code examples
pythonstatictypingmypy

What is an appropriate return type for an namedtuble, created within a function


i'm trying to static type some productive code, it looks something like this code snippet:

from collections import namedtuple
from typing import Dict, Union, NamedTuple, Any


def read_attr(ident: str, attributes: Union[None, Dict[str, str]]):
    tbl_attr = namedtuple('tbl', ['id', 'attr'])
    if attributes:
        return tbl_attr(id=ident, attr=attributes)
    else:
        return tbl_attr(id=ident, attr=None)


tbl = read_attr(ident='ID1', attributes={'foo': 'bar'})

print(tbl.attr['foo'])

The namedtuble tbl_attr is created within the function and should be called by an other function. My question is: how to type the return -> correctly. From my perspective there a few options like -> object or ofc `Any.


Solution

  • Moving the namedtuple definition outside the function definition allows you to use it as a return type. See below

    tbl_attr = namedtuple('tbl', ['id', 'attr'])
    
    def read_attr(ident: str, attributes: Union[None, Dict[str, str]]) -> tbl_attr:
        if attributes:
            return tbl_attr(id=ident, attr=attributes)
        else:
            return tbl_attr(id=ident, attr=None)
    

    tbl = read_attr(ident='ID1', attributes={'foo': 'bar'})

    print(tbl.attr['foo'])