This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author xtreak
Recipients eric.smith, gsakkis, rhettinger, xtreak
Date 2019-04-19.05:01:37
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1555650097.75.0.799396517123.issue36662@roundup.psfhosted.org>
In-reply-to
Content
asdict method in the benchmark does a direct dictionary construction. Meanwhile dataclasses.asdict does more work in https://github.com/python/cpython/blob/e8113f51a8bdf33188ee30a1c038a298329e7bfa/Lib/dataclasses.py#L1023 . Hence in the example i.asdict() and asdict(i) are not equivalent.

import timeit
from dataclasses import dataclass, asdict

@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def asdict(self):
        data = {'name': self.name,
                'unit_price': self.unit_price,
                'quantity_on_hand': self.quantity_on_hand,
        }
        return data

i = InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)
setup = """from dataclasses import dataclass, asdict;
@dataclass
class InventoryItem:
    '''Class for keeping track of an item in inventory.'''
    name: str
    unit_price: float
    quantity_on_hand: int = 0

    def asdict(self):
        data = {'name': self.name,
                'unit_price': self.unit_price,
                'quantity_on_hand': self.quantity_on_hand,
        }
        return data

i = InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)"""

print("asdict(i)")
print(timeit.Timer("asdict(i)", setup=f"{setup}").timeit(number=1_000_000))
print("i.asdict()")
print(timeit.Timer("i.asdict()", setup=f"{setup}").timeit(number=1_000_000))
print("i.inlined_asdict()")
print(timeit.Timer("i.inlined_asdict(i)", setup=f"{setup}; i.inlined_asdict = asdict").timeit(number=1_000_000))

i.inlined_asdict = asdict
assert asdict(i) == i.asdict() == i.inlined_asdict(i)


./python.exe ../backups/bpo36662.py
asdict(i)
11.585838756000001
i.asdict()
0.44129350699999925
i.inlined_asdict()
11.858042807999999
History
Date User Action Args
2019-04-19 05:01:37xtreaksetrecipients: + xtreak, rhettinger, gsakkis, eric.smith
2019-04-19 05:01:37xtreaksetmessageid: <1555650097.75.0.799396517123.issue36662@roundup.psfhosted.org>
2019-04-19 05:01:37xtreaklinkissue36662 messages
2019-04-19 05:01:37xtreakcreate