Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

My solution to the Player class regex challenge using **kwargs:

This is more a solution than a question, but I saw others here trying to get the class to work with **kwargs so I thought I'd share my solution for others.

players = re.search(r'''
    ^(?P<last_name>[\w\s]+),\s    # Last name
    (?P<first_name>[\w\s]+):\s    # First name
    (?P<score>\d+)$    # Score
''', string, re.M|re.V)


class Player():

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

I like the idea of using **kwargs rather than naming the attributes explicitly. This makes the code more general purpose and flexible - if I add another group to my regex query, I don't have to update my class to accept the new attribute. Hope this is helpful to someone. Cheers!

1 Answer

It's important to note the syntax required to use this, as **kwargs expects multiple keyword arguments to be passed, but players will be a single Match object. If you want to get the keyword arguments, you can unpack a dictionary of the named groups by using groupdict() on the Match object:

new_player = Player(**players.groupdict())

Good call. I didn't play around with this after it passed the code challenge, so I didn't even think about how creating new class instances would work. Thanks!