Skip to content

Commit

Permalink
Add optimization for default on_setattr w/ no work to do
Browse files Browse the repository at this point in the history
Otherwise we'd end up with an explicit setattr every time.
  • Loading branch information
hynek committed Dec 13, 2021
1 parent fedc570 commit 7d4c184
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 5 deletions.
11 changes: 8 additions & 3 deletions src/attr/_make.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@
# Unique object for unequivocal getattr() defaults.
_sentinel = object()

_ng_default_on_setattr = setters.pipe(setters.convert, setters.validate)


class _Nothing(object):
"""
Expand Down Expand Up @@ -722,13 +724,16 @@ def __init__(
self._cls_dict["__delattr__"] = _frozen_delattrs

self._wrote_own_setattr = True
elif on_setattr == setters.validate:
elif on_setattr == _ng_default_on_setattr:
for a in attrs:
if a.validator is not None:
break
if a.converter is not None:
break
else:
# If class-level on_setattr is set to validating, but there's
# no field to validate, pretend like there's no on_setattr.
# If class-level on_setattr is set to convert + validate, but
# there's no field to convert or validate, pretend like there's
# no on_setattr.
self._on_setattr = None

if getstate_setstate:
Expand Down
10 changes: 8 additions & 2 deletions src/attr/_next_gen.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@
from attr.exceptions import UnannotatedAttributeError

from . import setters
from ._make import NOTHING, _frozen_setattrs, attrib, attrs
from ._make import (
NOTHING,
_frozen_setattrs,
_ng_default_on_setattr,
attrib,
attrs,
)


def define(
Expand Down Expand Up @@ -92,7 +98,7 @@ def wrap(cls):

# By default, mutable classes convert & validate on setattr.
if frozen is False and on_setattr is None:
on_setattr = [setters.convert, setters.validate]
on_setattr = _ng_default_on_setattr

# However, if we subclass a frozen class, we inherit the immutability
# and disable on_setattr.
Expand Down

0 comments on commit 7d4c184

Please sign in to comment.