Greetings,

This message is for those that would like to "play" with a more natural
looking syntax for units in Python.

First, a quick look:

> python -m ideas -t easy_units
Ideas Console version 0.0.23. [Python version: 3.10.2]

~>> import pint
~>> U = pint.UnitRegistry()
~>> walk = 3[km] + 100[m]
~>> walk
<Quantity(3.1, 'kilometer')>
~>> p1 = 1.0[N/m^2]
~>> p2 = 1.0[Pa]
~>> p1 == p2
True

==
Or, for those that prefer astropy to pint:

> python -m ideas -t easy_units
Ideas Console version 0.0.23. [Python version: 3.10.2]

~>> from astropy.units import m, km, N, Pa
~>> walk = 3[km] + 100[m]
~>> walk
<Quantity 3.1 km>
~>> p1 = 1.0[N/m^2]
~>> p2 = 1.0[Pa]
~>> p1 == p2
True

===
Or, I simply want to run a script, say
# example.py
import pint
units = pint.UnitRegistry()

print(1.0[km] + 2[m])

===
> python -m ideas example -t easy_units
1.002 kilometer

Note that it is "example" and not "example.py" that is run (imported).

======
To try these examples, you need to:

python -m pip install ideas

and either
python -m pip install pint
or
python -m pip install astropy

## How does it work?

"ideas" (https://github.com/aroberge/ideas; documentation at
https://aroberge.github.io/ideas/docs/html/)
is a library I created a few years ago to allow easy experiments with
variations on Python's syntax.
When a module is imported (or when some code is run in the modified
interpreter), it is
first transformed prior to execution. Users of ideas can define
transformations that operate:
1. on the source (text)
2. on the AST
3. on the bytecode.

If one uses simple source transformations (which is what I did for
easy_units), one
can see the transformed code prior to its execution in the interactive
console, using a "verbosity" flag
(-v or --verbosity)

> python -m ideas -t easy_units -v
Ideas Console version 0.0.23. [Python version: 3.10.2]

~>> import pint
~>> Units = pint.UnitRegistry()  # "Units" here is an arbitrary name
~>> walk = 3[km] + 100[m]
===========Transformed============
walk = 3 * Units.km + 100 * Units.m
-----------------------------
~>> p1 = 1.0[N/m^2]
===========Transformed============
p1 = 1.0 * Units.N/(Units.m**2)
-----------------------------
~>> p2 = 1.0[N/m**2]  # using ** instead of ^ for Python purists
===========Transformed============
p2 = 1.0 * Units.N/(Units.m**2)  # using ** instead of ^ for Python purists
-----------------------------

Admittedly, it is a quick hack and may very well be buggy. But it can be
fun to use! ;-)

André Roberge
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/CWOEZQ5YJXO3KKYFXO2DQVHLMBNUVXBG/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to