[New-bugs-announce] [issue36662] asdict/astuple Dataclass methods

George Sakkis report at bugs.python.org
Thu Apr 18 16:31:10 EDT 2019


New submission from George Sakkis <george.sakkis at gmail.com>:

I'd like to propose two new optional boolean parameters to the @dataclass() decorator, `asdict` and `astuple`, that if true, the respective methods are generated as equivalent to the module-level namesake functions.

In addition to saving an extra imported name, the main benefit is performance. By having access to the specific fields of the decorated class, it should be possible to generate a more efficient implementation than the one in the respective function. To illustrate the difference in performance, the asdict method is 28 times faster than the function in the following PEP 557 example:


	@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): 
	        return {
	            'name': self.name, 
	            'unit_price': self.unit_price, 
	            'quantity_on_hand': self.quantity_on_hand,
	        } 
	                           

	In [4]: i = InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)                           

	In [5]: asdict(i) == i.asdict()                                                                         
	Out[5]: True

	In [6]: %timeit asdict(i)                                                                               
	5.45 µs ± 14.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

	In [7]: %timeit i.asdict()                                                                              
	193 ns ± 0.443 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Thoughts?

----------
components: Library (Lib)
messages: 340511
nosy: gsakkis
priority: normal
severity: normal
status: open
title: asdict/astuple Dataclass methods
type: enhancement
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue36662>
_______________________________________


More information about the New-bugs-announce mailing list