Replies: 1 comment
-
|
Here's a solution: import pint
ureg = pint.UnitRegistry()
ureg.formatter.default_format = "~" # display abbreviated units
def typecast_string_args(*args):
"""Cast string arguments to pint.Quantity."""
casted_args = []
for arg in args:
if isinstance(arg,str):
casted_args.append(ureg(arg))
elif isinstance(arg,pint.Quantity):
casted_args.append(arg)
else:
raise TypeError("Arguments must be of type str or pint.Quantity.")
return casted_args
def rectangle_area(length: pint.Quantity | str, width: pint.Quantity | str) -> pint.Quantity:
"""Compute area of a rectange."""
length, width = typecast_string_args(length, width)
area = length * width
return area.to_base_units()Works when all arguments are strings, all arguments are pint.Quantity or mixed: rectangle_area(length=50 * ureg.cm, width=100 * ureg.inch)
rectangle_area(length="50 cm", width="100 inch")
rectangle_area(length=50 * ureg.cm, width="100 inch") |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I like to use Pint to write functions for unit-aware calculations:
While the above works great, I would also like to use the same function but also have it accept string arguments as well. This is mostly a matter of convenience.
Is there a recommended way to achieve this?
Beta Was this translation helpful? Give feedback.
All reactions