namedtuple suggestions

J

Jason R. Coombs

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
 
C

Calvin Spealman

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 :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top