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

208
Visualizações
or as a shortcut for if ... is not None else

Very often I will have assignments like:

data = {
    'a': var_a if var_a is not None else default_a,
    ...
}

This is somewhat verbose. I think this can be shortened to

data = {
    'a': var_a or default_a,
    ...
}

at least if I know that var_a will not take on a value like 0 or [].

Are there any downsides to using this shorter notation?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Bad if var_a is falsy. This includes the boolean False, zero of any numeric type and a few others. For example, [] or 'foo' prints 'foo'. I like the idea, maybe there is some other Pythonian way to make it work.

over 4 years ago · Santiago Trujillo Relatório

0

var_a or default_a is the usual way to do it when None is treated the same as any 'Falsy' values (0, [], False, ...).

If you specifically need to check for None, you could express it like this:

'a': (var_a,default_a)[var_a is None]

or at least avoid the not by reversing the order

'a': default_a if var_a is None else var_a 

If you're going to do this often, you could make a function to shorten the expression:

def noNone(v,d): d if v is None else v

...

'a': noNone(var_a,default_a)
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