PhysicalQuantities icon indicating copy to clipboard operation
PhysicalQuantities copied to clipboard

Conversion from string

Open PetteriAimonen opened this issue 1 year ago • 2 comments

Thanks for the cool library! It would be nice to have a function that can parse a PhysicalQuantity from a string.

For usage outside ipython, it would be nice if this was available under a short name, such as the already existing q().

A quick mock-up which just splits at whitespace:

from PhysicalQuantities import PhysicalQuantity, _Quantity, q
_Quantity.__call__ = lambda s, x: PhysicalQuantity(float(x.split()[0]), x.split()[1])
print(q("1 m") / q("1 s"))  # gives 1.0 m/s

It would also be useful for parsing string data loaded from files or input by user.

PetteriAimonen avatar Oct 30 '23 13:10 PetteriAimonen

Thanks for your interest :-) You can use transform_line from PhysicalQuantities.transform to do this, see: I use this here for example: https://github.com/juhasch/yamleins/blob/master/yamleins/init.py

juhasch avatar Nov 05 '23 10:11 juhasch

Yeah, though that requires eval() which is quite risky when loading untrusted files.

PetteriAimonen avatar Nov 05 '23 13:11 PetteriAimonen