Skip to content

Instantly share code, notes, and snippets.

@ramalho
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramalho/fd3d367e9d3b2a659faf to your computer and use it in GitHub Desktop.
Save ramalho/fd3d367e9d3b2a659faf to your computer and use it in GitHub Desktop.
collections.plainclass: a mutable alternative to namedtuple
"""
A class equivalent to the class statement below would be generated by this code:
>>> import collections
>>> Point = collections.plainclass('Point', 'x y')
"""
class Point(object):
__slots__ = ['x', 'y'] # save memory in the likely event there are many instances
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return 'Point({!r}, {!r})'.format(self.x, self.y)
def __eq__(self, other):
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.y
def __iter__(self, other): # support unpacking
yield self.x
yield self.y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment