Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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()
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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))
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda