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 
5
  • 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 Commented Feb 16, 2017 at 9:09
  • 1
    what is self.request.files - is it a dictionary ? Commented Feb 16, 2017 at 9: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. Commented Feb 16, 2017 at 9:13
  • @PM2Ring thanks for the tip Commented Feb 16, 2017 at 9:14
  • @Tarptaeya i am using Tornado request handler Commented Feb 16, 2017 at 9:17

1 Answer 1

8

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:.

Sign up to request clarification or add additional context in comments.

5 Comments

can you please elaborate, still in the phase of trying to wrap my head around python
I love the phrase "pokemon exception handling". :)
@Baig: I've linked to the appropriate documentation for dictionaries. You didn't tell us more about where self.request comes from, is this code from a Tornado request handler perhaps?
@MartijnPieters yes it is from Tornado request handler
@Baig: that's a standard Python dictionary, so any of the standard dictionary operations apply there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.