Search code examples
pythonnamedtuple

NamedTuple with default values


I'm trying to use a function with a parameter of namedTuple which has default values. I tried this. Is that somehow possible?

from typing import Optional, NamedTuple
    
Stats = NamedTuple("Stats", [("min", Optional[int]), ("max", Optional[int])])
    
def print(value1: Stats=None, value2: Stats=None):
    print("min: ", value1.min)
    print("max: ", value1.max)
        
print()

Solution

  • Rename your print() function, first you're using the built-in function name print which is bad style, secondly then you make a recursive call to print() inside print() (and I'm sure you meant to call the actual built-in print() inside function's body).

    Second, use collection.namedtuple class to implement actual type of tuple, like following:

    Also type annotations are not needed.

    Try it online!

    from collections import namedtuple
    
    StatsTup = namedtuple('Stats', ['min', 'max'], defaults = [3, 7])
        
    def printf(value1 = StatsTup(), value2 = StatsTup(max = 10)):
        print("min1: ", value1.min)
        print("max1: ", value1.max)
    
        print("min2: ", value2.min)
        print("max2: ", value2.max)
    
    printf()
    printf(StatsTup(12, 14), StatsTup(16, 18))
    

    Output:

    min1:  3
    max1:  7
    
    min2:  3
    max2:  10
    
    min1:  12
    max1:  14
    
    min2:  16
    max2:  18
    

    As you can see in code and output above I'm passing named tuple as default parameters to funcion. You can omit tuple's fields values if you provide defaults = [...] like I did. If you provide such defaults then you may provide no values to tuple like StatsTup() or some values like StatsTup(max = 123) or all values like StatsTup(min = 20, max = 35).


    Solution above works only starting with Python 3.7, for older versions of Python do following:

    Try it online!

    from collections import namedtuple
    
    StatsTup = namedtuple('Stats', 'min max')
    StatsTup.__new__.__defaults__ = (3, 7)
        
    def printf(value1 = StatsTup(), value2 = StatsTup(max = 10)):
        print("min1: ", value1.min)
        print("max1: ", value1.max)
    
        print("min2: ", value2.min)
        print("max2: ", value2.max)
    
    printf()
    printf(StatsTup(12, 14), StatsTup(16, 18))