rakibtg
rakibtg

Reputation: 5901

Printing value of a variable as a object name python

Here goes an newbie question on python.
From the following function

def singlereader(url, linkGlue):
    d = feedparser.parse(url)
    tmp = []
    for item in d.entries:
        tmp.append(item.linkGlue) # line 5
    return tmp

how would i use the variable value as the object name for "item" In line 5, i want to use the value of "linkGlue" variable.

Upvotes: 2

Views: 66

Answers (2)

Hai Vu
Hai Vu

Reputation: 40688

If I understood you correctly, use:

getattr(item, linkGlue)

in place of

item.linkGlue

Upvotes: 2

Abhijit
Abhijit

Reputation: 63707

I think the closest you can get here is to leverage operator.attrgetter or using the builtin getattr

def singlereader(url, linkGlue):
    from operator import attrgetter
    d = feedparser.parse(url)
    tmp = []
    for item in d.entries:
        #tmp.append(attrgetter(linkGlue)(item)) # line 5
        tmp.append(getattr(item, linkGlue))
    return tmp

Upvotes: 1

Related Questions