2

I'm creating a json data source for Grafana in Python. It will grab information from JIRA and present is as a table to Grafana. I want the creation of the table to be dynamic so I want to be able to dynamically assign the fields I grab. The only way I've found that works so far is using eval()...

Can someone point me to a better solution? I've looked at getattr and setattr but either I don't understand how to use it or it doesn't do what I need..

Below example uses it only for priority:

priority = 'issue.fields.priority.name'

for issue in self.jira.search_issues(jql, maxResults=False):
    if issue.fields.assignee:
        issuelist.append([issue.key, issue.fields.assignee.displayName, eval(priority)])
    else:
        issuelist.append([issue.key, 'Unassigned', eval(priority)])
martineau
  • 119,623
  • 25
  • 170
  • 301
  • Possible duplicate of [How to use a dot "." to access members of dictionary?](https://stackoverflow.com/questions/2352181/how-to-use-a-dot-to-access-members-of-dictionary) – snakecharmerb Nov 16 '19 at 12:51

1 Answers1

2

IIUC, you could use getattr in the following way:

Setup

class Priority:

    def __init__(self, name):
        self.name = name


class Fields:

    def __init__(self, priority):
        self.priority = priority

class Issue:

    def __init__(self, fields):
        self.fields = fields

Code

from functools import reduce

priority = 'issue.fields.priority.name'
issue = Issue(Fields(Priority("high")))

print(eval(priority))
print(reduce(getattr, priority.split('.')[1:], issue))

Output

high
high

So in your code you could change:

issuelist.append([issue.key, 'Unassigned', eval(priority)])

to:

issuelist.append([issue.key, 'Unassigned', reduce(getattr, priority.split('.')[1:], issue)])
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76