4 ms·
Unless you really need to iterate over your class attributes I see no reason to do this. If you really want to save yourself the extra typing, could just as eas
by nerdponx 9y ago
Unless you really need to iterate over your class attributes I see no reason to do this. If you really want to save yourself the extra typing, could just as easily write a "make_slotted_class" factory function or a "SlottedType" metaclass that generates these classes with the same syntax as namedtuple/NamedTuple.
Edit: I stand corrected. There's no easy way (that I'm aware of) to generate an __init__ method in Python without resorting to string manipulation. Perhaps you could do it at the C level, but that defeats the purpose IMO.
- shakna 9y agoUse "type".[0] The last argument should be the dict that __INIT__ is usually responsible for creating. [0] https://jeffknupp.com/blog/2013/12/28/improve-your-python-metaclasses-and-dynamic-classes-with-type/ https://jeffknupp.com/blog/2013/12/28/improve-your-python-me...
- nerdponx 9y agoNot quite, AFAIU. The last argument is actually a dict of class attributes, one of which is the __init__ method. You can hack around it a few different ways (e.g. creating __init__ as a closure over the slot names and then inserting it into that 3rd argument), but none of them generate a proper init method. I'm planning on trying again tonight and I will probably blog my results on Friday. I'll read over that post carefully in case there's something I missed about type() and metaclasses.
- shakna 9y agoGood luck! Last time I approached this was generating classes for Pyramid, an it was hell, because it was incredibly poorly documented, and the community view was that metaprogramming was the devil's work. Community has started to shift, so there's a few more resources, but things don't behave exactly as expected so you will run into issues here and there. Hopefully you can add to the knowledge out there!