-
-
Save Tinche/372796f6e0e899ba099810981d5da541 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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