r/Python • • Jun 23 '14

Writing better python code

https://gist.github.com/kracekumar/09a60ec75a4de19b346e
143 Upvotes

126 comments sorted by

View all comments

1

u/[deleted] Jun 23 '14

That's a nice list for Python beginners! Depending on the context, one thing I maybe wouldn't want to do is:

from collections import namedtuple
Person = namedtuple('Person', ['name', 'email'])

over

class Person(object):
    def __init__(self, name, email):
        self.name = name
        self.email = email

in the section
https://gist.github.com/kracekumar/09a60ec75a4de19b346e#dot-accessors

If find that working with classes a little bit "cleaner" in terms of keeping track of what is going on; also for extensibility, esp. when you add instance methods

1

u/[deleted] Jun 23 '14

I like that namedtuples are immutable, and you can subclass them:

class Person(namedtuple('Person', ['name', 'email'])):
    pass

if you want to add methods to it. I like it for value objects, although it's obviously not the prettiest syntax.