By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,826 Members | 1,135 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,826 IT Pros & Developers. It's quick & easy.

namedtuple suggestions

P: n/a
I see a new function in (python 2.6) lib/collections called
namedtuple. This is a great function. I can see many places in my
code where this will be immensely useful.

I have a couple of suggestions.

My first suggestion is to use self.__class__.__name__ instead of the
hard-coded typename in __repr__, so that subclasses don't have to
override these methods just to use the correct name.

def __repr__(self):
return self.__class__.__name__ + '(%(reprtxt)s)' %% self
\n

My other suggestion, which is perhaps more intrusive, would be to
implement the underlying class as a metaclass, rather than
constructing and exec'ing a string. This would make the code more
readable (as there wouldn't be format string substitions in the class
definition, and the code could be interpreted by editors for syntax
highlighting, indentation support, etc).

I'm willing to take up the latter effort if there's agreement this
could be included in the release.

Regards,
Jason R. Coombs
Jun 27 '08 #1
Share this Question
Share on Google+
1 Reply

P: n/a
On Jun 13, 2008, at 11:17 AM, Jason R. Coombs wrote:
I see a new function in (python 2.6) lib/collections called
namedtuple. This is a great function. I can see many places in my
code where this will be immensely useful.

I have a couple of suggestions.

My first suggestion is to use self.__class__.__name__ instead of the
hard-coded typename in __repr__, so that subclasses don't have to
override these methods just to use the correct name.

def __repr__(self):
return self.__class__.__name__ + '(%(reprtxt)s)' %% self
\n
I feel like a large point of NamedTuple is for those cases where you
need a small object with some attributes _without_ creating a
subclass. Useful for mocks, for example, or when you need to trick a
function into dealing with a quick proxy or stub. If a large point is
not needing to create a class but instead creating a cheap object,
should it be a good idea to then subclass the very thing that was
intended to help you avoid creating a class in the first place? What
do you gain subclassing it?

However, I always think a repr reflecting a type name should reflect
the correct type, so I'm not disagreeing on that point. But, just
don't use concating :-)
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.