attrs/attr/_funcs.py

70 lines
1.6 KiB
Python
Raw Normal View History

2015-01-27 16:53:17 +00:00
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
import copy
2015-01-27 16:53:17 +00:00
def ls(cl):
"""
Returns the list of ``attrs`` attributes for a class.
:param cl: Class to introspect.
:type cl: type
:raise TypeError: If *cl* is not a class.
:raise ValueError: If *cl* is not an ``attrs`` class.
:rtype: :class:`list` of :class:`attr.Attribute`
2015-01-27 16:53:17 +00:00
"""
if not isinstance(cl, type):
raise TypeError("Passed object must be a class.")
2015-01-27 16:53:17 +00:00
attrs = getattr(cl, "__attrs_attrs__", None)
if attrs is None:
raise ValueError("{cl!r} is not an attrs-decorated class.".format(
2015-01-27 16:53:17 +00:00
cl=cl
))
return copy.deepcopy(attrs)
2015-01-27 16:53:17 +00:00
def to_dict(inst, recurse=True):
2015-01-27 16:53:17 +00:00
"""
Return the ``attrs`` attribute values of *i* as a dict. Optionally recurse
into other ``attrs``-decorated classes.
:param inst: Instance of a ``attrs``-decorated class.
:param recurse: Recurse into classes that are also ``attrs``-decorated.
:type recurse: bool
:rtype: :class:`dict`
2015-01-27 16:53:17 +00:00
"""
attrs = ls(inst.__class__)
2015-01-27 16:53:17 +00:00
rv = {}
for a in attrs:
v = getattr(inst, a.name)
if recurse is True and has(v.__class__):
2015-01-27 16:53:17 +00:00
rv[a.name] = to_dict(v, recurse=True)
else:
rv[a.name] = v
return rv
2015-01-28 10:15:40 +00:00
def has(cl):
2015-01-28 10:15:40 +00:00
"""
Check whether *cl* is a class with ``attrs`` attributes.
:param cl: Class to introspect.
:type cl: type
:raise TypeError: If *cl* is not a class.
:rtype: :class:`bool`
2015-01-28 10:15:40 +00:00
"""
try:
ls(cl)
except ValueError:
2015-01-28 10:15:40 +00:00
return False
else:
return True