2 ms·
namedtuple is awesome, until you realise it works internally by using eval and generating the source code of a class.
by TazeTSchnitzel 15y ago
namedtuple is awesome, until you realise it works internally by using eval and generating the source code of a class.
- chimeracoder 15y agoAnd Lisps work internally by generating lists and evaluating those, but you don't see me complaining about macros! In all seriousness, though, if I really wanted a functional implementation, I wouldn't be using Python. It's more just nice to know that I can create an object that's immutable and which functions more or less like a CLOS object, so that I can think in that mindset instead. Also, I believe it doesn't come with all of the hidden functions that it would otherwise. In the end, if I really cared, I'd actually write a wrapper around the type() function.
- mattdeboard 15y agonamedtuple is still awesome. The fact that it's eval'ing a string to initialize it doesn't make that any less the case. However, I'll agree that it would be disingenuous to say it's not a little peculiar, and surprising to see the source for it :)
- slig 15y agoWhy does it do that, instead of some other more pythonic way?
- benhoyt 15y agoSee also http://bugs.python.org/issue3974 http://bugs.python.org/issue3974, where someone submits a patch for namedtuple that doesn't use exec. The maintainers reject it as less clear and probably slower. I agree there is "nothing unholy in using exec", though I found this weird at first too.