We're a community of 1077K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,076,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

How to pass *args to attrgetter?

I have a simple class that stores attributes:

In [1]: class Test(object):
   ...:     a=10
   ...:     b=20

I have a function that returns attributes using attrgetter, and it accepts these through the args parameter to allow a user to pass various attribute fieldnames in. For example:

In [4]: def getstuff(*args):
   ...:     return attrgetter(args)

I can manually pass multiple arguments to an attrgetter and return the attributes from my class:

In [10]: f=attrgetter('a','b')

In [11]: f(test)
Out[11]: (10, 20)

However, my getstuff function doesn't work because args is a list and attrgetter takes only comma separated strings:

n [18]: f=getstuff('a','b')

In [19]: f(test)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-efe923d88401> in <module>()
----> 1 f(test)

TypeError: attribute name must be a string

Aka, the problem is args is being converted into a list. How do I get a list, say ['a', 'b'] into the attrgetter? attrgetter(['a','b']) ---> attrgetter('a','b')

Thanks

2
Contributors
2
Replies
17 Hours
Discussion Span
9 Months Ago
Last Updated
3
Views
Question
Answered
hughesadam_87
Posting Whiz in Training
274 posts since May 2009
Reputation Points: 67
Solved Threads: 12
Skill Endorsements: 1

you use the * operator on the list: attr_gen = attrgetter(*my_list)

griswolf
Veteran Poster
1,176 posts since Apr 2010
Reputation Points: 344
Solved Threads: 262
Skill Endorsements: 1

Thanks man. I suppose the * notation can be used anytime this is a problem then.

hughesadam_87
Posting Whiz in Training
274 posts since May 2009
Reputation Points: 67
Solved Threads: 12
Skill Endorsements: 1
Question Answered as of 9 Months Ago by griswolf

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0628 seconds using 2.73MB