Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

204
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!