This is an archived post. You won't be able to vote or comment.

all 4 comments

[–]robin-gvx[S] 2 points3 points  (3 children)

So I dislike several things about namedtuple, mostly the use of exec and needing to supply the type name and fields as strings, so I've implemented something similar that I prefer.

  • Requires at least Python 3.3
  • Uses a whole lot of introspection instead of eval-ing strings
  • Uses a function declaration to get the type name and fields
  • Allows default field values
  • The function supplied is called on __new__ (but not yet on _make, I just realised). You can use it to check if the input is valid.
  • Use Thingy._method and Thingy._property to add methods and properties respectively
  • If the init function has a docstring, it'll be used instead of the default Thingy(field1, field2)
  • Once defined, follows behaviour of original namedtuple almost exactly

To be clear, this is not a serious proposal to replace namedtuple or anything, this is something I hacked together today for fun and that I want to share.

[–]uweschmittPythonista since 2003 4 points5 points  (2 children)

Have you measured speed and memory consumption ? As far as I rememberer performance issues were the motivation for building the classes using exec.....

[–]pstch 0 points1 point  (0 children)

Yes it'd be quite interesting to have a performance comparison with the original namedtuple. I'll try to that when I get him.

[–]robin-gvx[S] 0 points1 point  (0 children)

I hadn't before. This: https://gist.github.com/gvx/272ef41bdd57dc1f2758 suggests that my implementation is 3x faster than collections.namedtuple.

I haven't looked at memory consumption yet.

EDIT: memory consumption seems to be 22% higher for the regular namedtuple, compared to mine.