From 588fe4801907ad5290d64aace712e823de2d6402 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tin=20Tvrtkovi=C4=87?= Date: Mon, 8 Aug 2016 08:44:30 +0200 Subject: [PATCH] Simplify asdict and has (#48) --- CHANGELOG.rst | 2 ++ src/attr/_funcs.py | 11 +++-------- tests/test_funcs.py | 2 +- 3 files changed, 6 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f9b0a2ae..512e88be 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -13,6 +13,8 @@ Changes: - ``attr.asdict``\ 's ``dict_factory`` arguments is now propagated on recursion. `#45 `_ +- ``attr.asdict`` and ``attr.has`` are significantly faster. + `#48 `_ ---- diff --git a/src/attr/_funcs.py b/src/attr/_funcs.py index 07f4495d..a1461a35 100644 --- a/src/attr/_funcs.py +++ b/src/attr/_funcs.py @@ -3,7 +3,7 @@ from __future__ import absolute_import, division, print_function import copy from ._compat import iteritems -from ._make import Attribute, NOTHING, fields +from ._make import Attribute, NOTHING, _fast_attrs_iterate def asdict(inst, recurse=True, filter=None, dict_factory=dict): @@ -30,7 +30,7 @@ def asdict(inst, recurse=True, filter=None, dict_factory=dict): .. versionadded:: 16.0.0 *dict_factory* """ - attrs = fields(inst.__class__) + attrs = _fast_attrs_iterate(inst) rv = dict_factory() for a in attrs: v = getattr(inst, a.name) @@ -71,12 +71,7 @@ def has(cl): :rtype: :class:`bool` """ - try: - fields(cl) - except ValueError: - return False - else: - return True + return getattr(cl, "__attrs_attrs__", None) is not None def assoc(inst, **changes): diff --git a/tests/test_funcs.py b/tests/test_funcs.py index 7dc47dd1..d7b3193e 100644 --- a/tests/test_funcs.py +++ b/tests/test_funcs.py @@ -15,12 +15,12 @@ from . import simple_classes, nested_classes from attr._funcs import ( asdict, assoc, - fields, has, ) from attr._make import ( attr, attributes, + fields, ) MAPPING_TYPES = (dict, OrderedDict)