Newbie Python Question

Status
Not open for further replies.
I'm building a class with several optional attributes which can be set inline with the instance creation. Which is preferable?

Pass the attributes directly within __init__:
Code:
class Foo(object):
    def __init__(self, 
            name, 
            bar1 = 0, 
            bar2 = 0, 
            bar3 = 0, 
            bar4 = 0, 
            notes = '', 
            comment = ''):
        self.name = name
        self.bar1 = bar
        self.bar2 = bar2
        self.bar3 = bar3
        self.bar4 = bar4
        self.notes = notes
        self.comment = comment

Or use **kwargs and check for each potential value:
Code:
class Foo(object):
    def __init__(self, name, **kwargs):
        self.name = name
        self.bar1 = kwargs['bar1'] if 'bar1' in kwargs else 0
        self.bar2 = kwargs['bar2'] if 'bar2' in kwargs else 0
        self.bar3 = kwargs['bar3'] if 'bar3' in kwargs else 0
        self.bar4 = kwargs['bar4'] if 'bar4' in kwargs else 0
        self.notes = kwargs['notes'] if 'notes' in kwargs else ''
        self.comment = kwargs['comment'] if 'comment' in kwargs else ''

I can see why the second method might be a bit more expensive, but it's not as if there's a lot of data being stored, and (self, name, **kwargs) looks cleaner and is easier to change if I need to add more arguments down the line.
 

Jonathon

Ars Legatus Legionis
17,645
Subscriptor
I'd rather see the first unless you have some obscenely large number of optional arguments; the first gives me more useful information if I'm looking at autogenerated documentation or using an IDE's code completion (because the list of valid parameters is encoded in the function definition). The second requires me to look at the body of the method (or whatever documentation you write, manually) to see what parameters I can pass.

That said, you'll find both styles in the modules that ship with the Python standard library.
 
I had thought about that, but the only one that wouldn't need to be set during creation is 'comments', so I may as well just put it out there. Realistically, I might be adding one or two more variables, one of which is a boolean, but not a bunch more.

I hadn't realized that parts of the standard library use kwargs in the __init__, probably because I haven't really looked at the individual modules that much. There's just so much "Right Way" philosophy in Python that I wanted to double-check the "Right Way" when you have more than three or four attributes that get passed to an instance creation.
 

Jonathon

Ars Legatus Legionis
17,645
Subscriptor
[url=http:/civis/viewtopic.php?p=27181259#p27181259:8oca45ws said:
Jokotai[/url]":8oca45ws]I had thought about that, but the only one that wouldn't need to be set during creation is 'comments', so I may as well just put it out there. Realistically, I might be adding one or two more variables, one of which is a boolean, but not a bunch more.

I hadn't realized that parts of the standard library use kwargs in the __init__, probably because I haven't really looked at the individual modules that much. There's just so much "Right Way" philosophy in Python that I wanted to double-check the "Right Way" when you have more than three or four attributes that get passed to an instance creation.
There are a few spots where it does, but, after actually checking, it's not as common as I was remembering. Looks like most of them are cases where the exact names or number of potential optional keyword args aren't known (for example, urllib.URLopener uses kwargs in its __init__ to pass SSL client certificates). And, TBH, even that's a bit of a questionable use of kwargs-- probably better/more flexible to use a dictionary instead.

I'd stick with the first option (or, if you can, moving some of the options into properties or attributes) unless you have a good reason to do otherwise.
 
The hitchhiker's guide to python agrees with the recommendations here in the thread.

See #4 in the "function arguments" section http://docs.python-guide.org/en/latest/writing/style/#function-arguments

"these powerful techniques are to be used when there is a proven necessity to use them, and they should not be used if the simpler and clearer construct is sufficient to express the function’s intention."

Also note the PEP8 recommends not putting spaces between named arguments and their default values in general, which would apply to your barX arguments. See 3rd bullet under "Other recommendations" http://legacy.python.org/dev/peps/pep-0008/#other-recommendations

I've been very happy with the free pycharm community edition for my python editing and it can be configured to live-check that you're conforming to PEP8 style which I've found pretty handy in learning the recommended style.

edit: fixed 1st link
 
Status
Not open for further replies.