0

Current code:

error = dict.get("error", None)
if error:
    print(error)

Is there a way to place it on one line, e.g.:

print(error) if (error = dict.get("error", None))

In C you can assign a value, then compare, then print it out on one line:

if (a = 5) printf("%d",a);
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Friedpanseller
  • 654
  • 3
  • 16
  • 31
  • No, there isn't; your code is perfectly readable. Note that `None` is the default default value, so is redundant there. – jonrsharpe Jan 03 '19 at 21:53

4 Answers4

1

Instead of using a ternary print("" if not d.get("error") else d["error"]) you can use dict.get(key,default) and print() with a ternary telling end="" or end="\n" to avoid/use the newline after it:

d = {"error": "plenty"}  

print( d.get("error",""), end = "\n" if d.get("error","") else "")

This prints nothing (not even a newline due to end="") if the key is not present.

See Why dict.get(key) instead of dict[key]?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
1

In Python 3.8, you will be able to write

if error := dict.get("error", None):
    print(error)

Python does not have Perl-style statement modifiers, but since print is a function, you can write an expression statement like

print(error) if (error := dict.get("error", None)) else None

although I wouldn't recommend it. (Actually, I'm not entirely sure the assignment expressions defined by PEP-572 interact with a conditional expression. I haven't played with any reference implementations to test it, but I believe error will be in scope for the entire expression.)


A simple if statement like that, though, can be written on one line (although again, I wouldn't recommend it; PEP-8 explicitly frowns upon

if error := dict.get('error', None): print(error)

)

chepner
  • 497,756
  • 71
  • 530
  • 681
0

Building on the answer here you could possibly cram multiple expressions using a semicolon. Something like

error = my_dict.get("error", None); print(error) if error is not None else None

Should work, but I'm typing on my phone and can't test.

Andrew F
  • 2,690
  • 1
  • 14
  • 25
  • Just to agree with the comment above, cramming this into a one-liner feels like poor programming and should be avoided. Still, it is _possible_. Also, it's bad practice to overwrite the built in `dict` keyword with a variable. – Andrew F Jan 03 '19 at 21:57
0

You can simply use inline if else provided by python.

print('error') if dict.get("error") else 0

That it! Hope it helps:)

Mirza715
  • 420
  • 5
  • 15