Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/attr/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
asdict,
assoc,
has,
names,
)
from ._make import (
Attribute,
Expand Down Expand Up @@ -57,4 +58,5 @@
"set_run_validators",
"validate",
"validators",
"names",
]
15 changes: 15 additions & 0 deletions src/attr/_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,18 @@ def assoc(inst, **changes):
)
setattr(new, k, v)
return new


def names(cl):
"""
Returns the tuple of ``attrs`` attribute names for a class.

:param cl: Class to introspect.
:type cl: class

:raise TypeError: If *cl* is not a class.
:raise ValueError: If *cl* is not an ``attrs`` class.

:rtype: tuple of attr.ib names
"""
return tuple(a.name for a in fields(cl))
55 changes: 55 additions & 0 deletions tests/test_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
asdict,
assoc,
has,
names,
)
from attr._make import (
attr,
Expand Down Expand Up @@ -218,3 +219,57 @@ class C(object):
assert (
"y is not an attrs attribute on {cl!r}.".format(cl=C),
) == e.value.args


class TestNames(object):
"""
Tests for `names`.
"""
def test_empty(self):
"""
Empty classes returns empty tuple.
"""
@attributes
class C(object):
pass

assert names(C) == tuple()

def test_TypeError(self):
"""
Raises TypeError if argument is not a class.
"""
with pytest.raises(TypeError):
names(1)

def test_ValueError(self):
"""
Raises ValueError if argument is not an attrs class.
"""
class C(object):
name = 'value'

with pytest.raises(ValueError):
names(C)

def test_attr_names(self):
"""
Gives back tuple of names only for attr Attributes.
"""
@attributes
class C(object):
x = attr()
y = attr()

assert names(C) == ('x', 'y')

def test_mixed_names(self):
"""
Gives back tuple of names only for attr Attributes.
"""
@attributes
class C(object):
x = attr()
y = 42

assert names(C) == tuple('x')