How to avoid too many Try/except?

Asked

Viewed 65 times

1

I have the code below that plays values inside keys in a dictionary. However, I need several try / except so that the code works perfectly, since, in the absence of one of the fields, the code will return a Keyerror Exception and the code will break.

Is there a more optimized and/or simpler way to solve the problem?

Code:

issue_fmt = {}
issue_fmt['assignee'] = {}
issue_fmt['assignee']['display_name'] = ''
issue_fmt['reporter'] = {}
issue_fmt['reporter']['display_name'] = ''
issue_fmt['key'] = ''
issue_fmt['project'] = {}
issue_fmt['project']['name'] = ''

def format_doc(issue):

    try:
        issue_fmt['assignee']['display_name'] = issue['assignee']['display_name']
    except:
        issue_fmt['assignee']['display_name'] = ''
    try:
        issue_fmt['reporter']['display_name'] = issue['reporter']['display_name']
    except:
        issue_fmt['reporter']['display_name'] = ''
    try:
        issue_fmt['key'] = issue['key']
    except:
        issue_fmt['key'] = ''
    try:
        issue_fmt['description'] = issue['description']
    except:
        issue_fmt['description'] = ''
    try:
        issue_fmt['project']['name'] = issue['project']['name']
    except:
        issue_fmt['project']['name'] = '' 

    return dict(issue_fmt)

1 answer

7


The dictionary has a method get which you can take as the second parameter a value that will be returned when the fetched key does not exist. So instead:

try:
    issue_fmt['assignee']['display_name'] = issue['assignee']['display_name']
except:
    issue_fmt['assignee']['display_name'] = ''

Just you do

issue_fmt['assignee']['display_name'] = issue['assignee'].get('display_name', '')

So it would be:

def format_doc(issue):
    issue_fmt['assignee']['display_name'] = issue['assignee'].get('display_name', '')
    issue_fmt['reporter']['display_name'] = issue['reporter'].get('display_name')
    issue_fmt['key'] = issue.get('key', '')
    issue_fmt['description'] = issue.get('description', '')
    issue_fmt['project']['name'] = issue['project'].get('name', '')

    return dict(issue_fmt)

But other points should be considered:

  1. Why issue_fmt is defined outside the function and not within it?
  2. If issue_fmt is already a dictionary, why return dict(issue_fmt)?
  • Perfect, the get method solved my problem. Thanks! issue_fmt is set out just to simplify the example. Actually, it is read from another file. On the return, really is an unnecessary redundancy, I just fixed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.