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 gsakkis
Recipients gsakkis
Date 2019-04-18.20:31:10
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1555619470.94.0.171933894359.issue36662@roundup.psfhosted.org>
In-reply-to
Content
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?
History
Date User Action Args
2019-04-18 20:31:10gsakkissetrecipients: + gsakkis
2019-04-18 20:31:10gsakkissetmessageid: <1555619470.94.0.171933894359.issue36662@roundup.psfhosted.org>
2019-04-18 20:31:10gsakkislinkissue36662 messages
2019-04-18 20:31:10gsakkiscreate