In Python, what’s the best practice for creating multiple objects from the same class? For example:
(doc, grumpy, happy, sleepy, bashful, sneezy, dopey) = Dwarf(), Dwarf(), Dwarf(), Dwarf(), Dwarf(), Dwarf(), Dwarf()
This is pretty unwieldy. A generator expression can shorten it:
(doc, grumpy, happy, sleepy, bashful, sneezy, dopey) = (Dwarf() for i in range(7))
The for i in range(7)
bit seems like it ought to be unnecessary though. I've seen a suggestion of using ... = (object,)*7
, but that only works for immutable basic types (numbers, strings, tuples, etc.). If used for user classes, it will assign all names to the same object.
I'm mostly asking out of curiosity, though I do sometimes need this for test code. I've searched fairly extensively and haven't found a definitive answer.