2

I am new to Python and still learning the tricks.

How can i convert the following code to a single liner, is it possible in Python? There has to be a neat way of doing this.

try:
    image_file = self.request.files['image_path']
except:
    image_file = None
Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
Shairyar
  • 3,268
  • 7
  • 46
  • 86
  • There isn't such a thing as a single-line-try in Python. If the exception you're guarding against is a `KeyError` from a `dict`, then you could use [`get`](https://docs.python.org/2/library/stdtypes.html#dict.get) – khelwood Feb 16 '17 at 09:09
  • 1
    what is self.request.files - is it a dictionary ? – Anmol Gautam Feb 16 '17 at 09:10
  • 1
    BTW, using a naked `except` is generally not a good idea (unless it's at the end of a chain of named except clauses, and even then you probably want to re-raise the exception after printing a warning or performing some other processing). Always specify the exception(s) that you want to catch. – PM 2Ring Feb 16 '17 at 09:13
  • @PM2Ring thanks for the tip – Shairyar Feb 16 '17 at 09:14
  • @Tarptaeya i am using Tornado request handler – Shairyar Feb 16 '17 at 09:17

1 Answers1

7

You have a dictionary, use the dict.get() method to return a default value for missing keys:

image_file = self.request.files.get('image_path')

Also, do not use pokemon exception handling. You really don't need to catch them all here; if a key is missing, KeyError is raised, if you must use try..except should catch just that one exception with except KeyError:.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343