Skip to content

Instantly share code, notes, and snippets.

@Tinche

Tinche/t.py Secret

Last active November 29, 2016 23:40
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 Tinche/372796f6e0e899ba099810981d5da541 to your computer and use it in GitHub Desktop.
Save Tinche/372796f6e0e899ba099810981d5da541 to your computer and use it in GitHub Desktop.
import attr
from attr import fields
from attr.exceptions import AttrsAttributeNotFoundError
from attr.validators import instance_of, optional
@attr.s
class A:
"""A trivial class."""
a = attr.ib()
@attr.s
class B:
"""A less trivial class."""
b = attr.ib(validator=instance_of(str))
c = attr.ib(convert=int)
d = attr.ib(validator=optional(instance_of(float)))
e = attr.ib(default=1)
@attr.s
class C(B, A):
"""A big class."""
f = attr.ib(convert=str, default='f')
g = attr.ib(default=7)
h = attr.ib(validator=instance_of(int), default=8)
i = attr.ib(default=attr.Factory(lambda: b'11'))
def assoc(inst, **changes):
"""An optimized assoc."""
for a in fields(inst.__class__):
name = a.name
if name not in changes:
changes[name] = getattr(inst, name)
try:
return inst.__class__(**changes)
except TypeError as exc:
k = exc.args[0].split("'")[1]
raise AttrsAttributeNotFoundError(
"{k} is not an attrs attribute on {cl}."
.format(k=k, cl=inst.__class__))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment