Skip to content

Instantly share code, notes, and snippets.

@soplakanets
Created March 4, 2011 10:07
Show Gist options
  • Save soplakanets/854425 to your computer and use it in GitHub Desktop.
Save soplakanets/854425 to your computer and use it in GitHub Desktop.
Basic implementation of decorators to generate default str, repr and eq for class.
#!/usr/bin/env python
# coding: utf-8
def _str(o):
return "%s(%s)" % (o.__class__.__name__, ", ".join([("%s=%s" % (k, v)) for k, v in o.__dict__.items()]))
def default_str(cls):
setattr(cls, "__str__", _str)
return cls
def default_repr(cls):
setattr(cls, "__repr__", _str)
return cls
def default_eq(cls):
def _eq(this, other):
return this.__dict__ == other.__dict__
setattr(cls, "__eq__", _eq)
return cls
__all__ = ["default_str", "default_repr", "default_eq"]
if __name__ == '__main__':
from unittest import TestCase, main
class DecoratorsTest(TestCase):
def testDefaultStr(self):
@default_str
class Foo:
def __init__(self):
self.foo = "bar"
@default_str
class Bar:
def __init__(self):
self.foo = "bar"
self.bar = "bazz"
self.assertEquals("Foo(foo=bar)", str(Foo()))
self.assertEquals("Bar(foo=bar, bar=bazz)", str(Bar()))
def testDefaultRepr(self):
@default_repr
class Foo:
def __init__(self):
self.var1 = "foo"
self.var2 = "bar"
self.assertEquals("Foo(var1=foo, var2=bar)", repr(Foo()))
def testDefaultEq(self):
@default_eq
class Foo:
def __init__(self, var1, var2):
self.var1 = var1
self.var2 = var2
self.assertEquals(Foo(1,2), Foo(1,2))
self.assertNotEquals(Foo(1,2), Foo(3,4))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment