How to set field `pint.Quantity._magnitude` of existing object?

61 Views Asked by At

Using the pint library, I profiled my code and found a bottleneck is creating new Quantity objects using the constructor like this:

import pint
ureg = pint.UnitRegistry()
...
quantity = pint.Quantity(-2.5, ureg.kcal / ureg.mol)
quantities[i] = quantity

I have a list quantities of Quantity objects whose size doesn't change. I would like to edit the Quantity objects in-place to try to speed this up. Since the units will never change (always will be kcal/mol), I had hoped to be able simply to set the magnitude instead:

quantities[i].magnitude = -2.5

However, this results in this error:

---> 43 quantities[i].magnitude = -2.5

AttributeError: can't set attribute

I know Quantity objects are mutable, so I hope there is some way to edit the magnitude attribute, but I can't tell how from the documentation. I don't see a method to do it.

Of course, Python lets you edit "private" fields directly, so I could do this:

quantities[i]._magnitude = -2.5

This does speed up the code significantly. But presumably that field is private for a reason, and something might break if I try to set _magnitude directly, i.e., perhaps some other derived fields don't get recomputed that should be?

0

There are 0 best solutions below