Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

203
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda