Skip to content

Commit

Permalink
Fix auto_attrib=None behavior when maybe_cls=None (#675)
Browse files Browse the repository at this point in the history
* Fix auto_attrib=None behavior when maybe_cls=None

* Update tests/test_next_gen.py

Co-authored-by: David Euresti <github@euresti.com>

Co-authored-by: Hynek Schlawack <hs@ox.cx>
  • Loading branch information
euresti and hynek committed Aug 23, 2020
1 parent d02b76d commit 4cfd52d
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 8 deletions.
25 changes: 17 additions & 8 deletions src/attr/_next_gen.py
Expand Up @@ -50,9 +50,9 @@ def define(
.. versionadded:: 20.1.0
"""

def do_it(auto_attribs):
def do_it(cls, auto_attribs):
return attrs(
maybe_cls=maybe_cls,
maybe_cls=cls,
these=these,
repr=repr,
hash=hash,
Expand All @@ -74,12 +74,21 @@ def do_it(auto_attribs):
)

if auto_attribs is not None:
return do_it(auto_attribs)

try:
return do_it(True)
except UnannotatedAttributeError:
return do_it(False)
return do_it(maybe_cls, auto_attribs)

def wrap(cls):
# Making this a wrapper ensures this code runs during class creation.
try:
return do_it(cls, True)
except UnannotatedAttributeError:
return do_it(cls, False)

# maybe_cls's type depends on the usage of the decorator. It's a class
# if it's used as `@attrs` but ``None`` if used as `@attrs()`.
if maybe_cls is None:
return wrap
else:
return wrap(maybe_cls)


mutable = define
Expand Down
25 changes: 25 additions & 0 deletions tests/test_next_gen.py
Expand Up @@ -101,6 +101,31 @@ class OldSchool:

assert OldSchool(1) == OldSchool(1)

# Test with maybe_cls = None
@attr.define()
class OldSchool2:
x = attr.field()

assert OldSchool2(1) == OldSchool2(1)

def test_auto_attribs_detect_annotations(self):
"""
define correctly detects if a class has type annotations.
"""

@attr.define
class NewSchool:
x: int

assert NewSchool(1) == NewSchool(1)

# Test with maybe_cls = None
@attr.define()
class NewSchool2:
x: int

assert NewSchool2(1) == NewSchool2(1)

def test_exception(self):
"""
Exceptions are detected and correctly handled.
Expand Down

0 comments on commit 4cfd52d

Please sign in to comment.