hgrecco / pint

Operate and manipulate physical quantities in Python
http://pint.readthedocs.org/
Other
2.4k stars 472 forks source link

Proposal: Allow ureg.wraps to convert string arguments #711

Closed lewisamarshall closed 4 years ago

lewisamarshall commented 6 years ago

Hi! I really like pint, and I'm designing a package that uses it for scientific computations. I'd like to propose an extension that I would find useful. This extension would automatically convert strings to Quantities on wrapping functions. Example code is below.

@ur.wraps(ur.second, ur.meter, strict=False)
def test(l):
    return l*2

test('1 mm')
# Actual result:    <Quantity(1 mm1 mm, 'second')>
# Desired result: <Quantity(0.002, 'second')>

This behavior could be placed behind another keyword argument, for example convert_strings=True.

The use case here is as follows:

If you think this is a good idea, I'd be happy to submit a PR for it.

jondoesntgit commented 6 years ago

As far as using the same registry, I usually type from pint import _DEFAULT_REGISTRY as u

jondoesntgit commented 6 years ago

Can you describe your workflow a little more? If users already understand Pint, can they use Quantity objects? Are you parsing text files?

lewisamarshall commented 6 years ago

Sure. The module I'm talking about is ebb, which is a pipe flow calculation tool.

The tutorial is here. https://nbviewer.jupyter.org/github/lewisamarshall/ebb/blob/tutorial_update/tutorial.ipynb

The intended audience is fluidic engineers with novice or higher python skill. Anyone interested in performing a fluid flow calculation should be able to import the module and start modeling in a jupyter notebook.

This module is a work in progress. It has the functionality that I'm interested in, but through a different mechanism. At the time I started working on it, I wasn't aware of ureg.wraps.

Typical code that would use the proposed functionality is below.

from ebb.pipes import CircularPipe; from ebb.fluids import Water
pipe = CircularPipe(radius='1 mm', length='10 cm')
pipe.fluid(Water)
print(pipe.maximum_velocity(pressure='0.1 psi'))

This code would also work if the strings were replaced by Quantities. The output of functions are all Quantities.

lewisamarshall commented 6 years ago

Regarding _DEFAULT_REGISTRY, I appreciate this information, but it seems like it requires more knowledge from the end user rather than less.

Thanks for taking the time to consider this! ✨

hgrecco commented 6 years ago

I think we can accept that PR that parses strings into quantities within wraps but only if strict=True.