Skip to main content

Physical unit literals for Jupyter and IPython

Project description

unit-syntax extends the Python language in Jupyter/IPython to support expressions with physical units:

>>> speed = 5 meters/second
>>> (2 seconds) * speed
10 meter

Behind the scenes this is translated into standard Python that uses the excellent Pint units library.

Getting Started

Install the package:

$ pip install unit-syntax

To enable unit-syntax in a Jupyter/IPython session run:

import unit_syntax
unit_syntax.enable_ipython()

Note: in Jupyter this must be run in its own cell before any units expressions are evaluated.

Usage

An interactive notebook to play around with units

Units apply to the immediately preceding value:

1.21 gigawatts # literal number
(30 + 7) watts # parenthesized expression
[5, 7] meters # literal list
(9, 11) lumens # literal tuple
# variable reference
y becquerel
position.x attoparsec
velocity[player_id] meters/s

Units are parsed greedily and bind only to the immediately preceding value:

x * 5 meters # x * (5 meters), not (x*5) meters

Quantities can be converted to another measurement system:

>>> (88 miles / hour) furlongs / fortnight
236543.5269120001 furlong / fortnight
>>> (0 degC) degF
31.999999999999936 degree_Fahrenheit

It's highly recommended to parenthesize any complex that include units. For example:

1 meters * sin(degrees)

This is desugared to Quantity(1, "meters * sin(degrees)"), when you probably wanted (1 meters) * sin(degrees).

Units may not begin with parentheses (consider the possible interpretations of x (meters)). Parentheses are allowed anywhere else:

x (newton meters)/(second*kg) # parsed as a function call, will result in a runtime error
x newton meters/(second*kg) # ok

Syntax Details

The full grammar for units is:

units:
    | units '/' units_group
    | units '*' units_group
    | units units_group
    | units '**' NUMBER
    | NAME

units_group:
    | '(' units ')'
    | units

Compound units allow the usual operators multiplication, division, and exponentiation with the usual precedence rules. Adjacent units without an operator are treated as multiplication.

Help!

If you're getting an unexpected result, try using unit_syntax.enable_ipython(debug_transform=True). This will log the transformed python code to the console.

Why? How? Are you sure this a good idea?

I like using Python with Jupyter Notebook as a calculator for physical problems and often wish it had the clarity and type checking of explicit units. Pint is great, but its (necessary) verbosity makes it hard to see the underlying calculation that's going. Ultimately I want something that is as readable as what I'd write on paper using normal notation.

unit-syntax is an IPython custom input transformer that rewrites expressions with units into calls to pint.Quantity. The parser is a lightly modified version of the Python grammar using the same parser generator (pegen) as Python itself.

Should you use this? There are tradeoffs. When using unit-syntax as an interactive calculator the clarity of explicit units improves both readability and correctness. However, the new syntax also introduces new opportunities for error if an expression is parsed in an unexpected way. Usually this is obvious when used interactively, but it's something to be aware of.

unit-syntax cannot (currently) be used for standalone python scripts outside of IPython/Jupyter, but that's in principle possible through meta_path import hooks.

Prior Art

The immediate inspriration of unit-syntax is a language called Fortress from Sun Microsystems. Fortress was intended as a modern Fortran, and had first-class support for units in both the syntax and type system.

F# (an OCaml derivative from Microsoft) also has first class support for units.

The Julia package Unitful.jl

A long discussion on the python-ideas mailing list about literal units in Python.

Development

To regenerate the parser:

python -m pegen grammar.txt -o unit_syntax/parser.py

Running tests:


$ poetry install --with dev
$ poetry run pytest

Future work and open questions

  • Test against various ipython and python versions
  • Support standalone scripts through sys.meta_path
  • Check units at parse time
  • Unit type hints, maybe checked with @runtime_checkable. More Pint typechecking discussion
  • Expand the demo Colab notebook
  • Typography of output
  • Its too easy to get an unexpected parse if you forget parentheses.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

unit_syntax-0.1.8.tar.gz (20.6 kB view details)

Uploaded Source

Built Distribution

unit_syntax-0.1.8-py3-none-any.whl (18.7 kB view details)

Uploaded Python 3

File details

Details for the file unit_syntax-0.1.8.tar.gz.

File metadata

  • Download URL: unit_syntax-0.1.8.tar.gz
  • Upload date:
  • Size: 20.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for unit_syntax-0.1.8.tar.gz
Algorithm Hash digest
SHA256 32bdedb32eef927032f6756b87a48561a888476fc1383f64a426ce7c3c3bbbf8
MD5 38f33a6a050089e0c1c82d74e0b70e8e
BLAKE2b-256 28cc5b68d2262d0d394ea11c68635d6574e659c60ae094490ba2e0a99de98174

See more details on using hashes here.

File details

Details for the file unit_syntax-0.1.8-py3-none-any.whl.

File metadata

  • Download URL: unit_syntax-0.1.8-py3-none-any.whl
  • Upload date:
  • Size: 18.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/4.0.2 CPython/3.11.4

File hashes

Hashes for unit_syntax-0.1.8-py3-none-any.whl
Algorithm Hash digest
SHA256 041f882ace6c523a77700a461751c2bb4c0abb5a3bebd00c7babebd45d5c2300
MD5 2900f4747af065d4c21e86e66ae020fe
BLAKE2b-256 13667a857221a6692f13d7e26b389a80c3e15f30ed129c3248ff4fa7f3aebcd2

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page