Skip to main content

forallpeople:
The world's units
at your fingertips

"For all people. For all time."
Nicolas de Caritat (Marquis de Condorcet),
in regards to the creation of the metric (SI) system.

Github Stars Github Pages Documentation Link GitHub Issues or Pull Requests

forallpeople is a Python library for providing access to units-aware calculations through the SI units system, and other units defined by the SI sytem (e.g. US customary units, Imperial).

While there are many other units libraries available for Python, forallpeople is unique in the following ways:

  1. Physical quantities are automatically reduced during multiplication and division.
  2. Physical quantities that are completely cancelled out return just a number (instead of a dimensionless unit).
  3. Physical quantities carry their own dimension vectors and, as such, their definitions exist independently of the units environment they are in.
  4. When loaded, the units variables can either be dynamically pushed to the module namespace or to the top-level namespace. This allows for faster code writing that looks like this a = 5 * kg instead of a = 5 * si.kg
  5. Released on PyPI on the day the new definition of the kilogram was adopted by the world on World Metrology Day, 20 May 2019.

Installing

You can install using pip:

pip install forallpeople

Basic usage 1: Module-level namespace

The most basic use is just to import the library:

import forallpeople as si

This will import the Physical class. It is the primary class in the module and is used to describe all physical quantities. Physical instances are immutable.

Upon import, the SI base units are instantiated and are available in the namespace as the following variables:

  • si.m - meter
  • si.kg - kilogram
  • si.s - second
  • si.A - ampere
  • si.cd - candela
  • si.K - kelvin
  • si.mol - mole

Basic Usage 1

Loading an environment

si.environment('default', [top_level=False])

This will load the 'default.json' file within the forallpeople module that describes the SI derived units, the units created by compounding the base units (e.g. Newton, Pascal, Celsius, Watt, Joule, etc.).

When you load an environment, whether it is the default environment or one you define, the representation of the units will change to fit the definitions in the environment. Environment definitions are dimensional, meaning, if you end up with a Physical of a dimension that matches a dimension in the environment, then the repr() of that instance will change to match the dimensioned unit in the environment.

It is important to note that, no matter what environment is loaded or not loaded, your Physical instances will always carry their value in the SI base units, e.g.:

>>> pressure = force / area
>>> pressure = 208.333 Pa
>>> pressure.repr
>>> 'Physical(value=208.33333333333334, dimensions=Dimensions(kg=1, m=-1, s=-2, A=0, cd=0, K=0, mol=0), factor=1, _precision=3)'

Additionally, when you load an environment, the units defined in the environment will be instantiated as Physical and you can utilize them as variables in calculations.

The 'default' environment defines and loads the following units as variables into the module namespace:

  • si.N - newton
  • si.Pa - pascal
  • si.J - joule
  • si.W - watt
  • si.C - coulomb
  • si.V - volt
  • si.F - farad
  • si.Ohm - ohm
  • si.S - siemens
  • si.Wb - weber
  • si.T - tesla
  • si.H - henry
  • si.lm - lumen
  • si.lx - lux
  • si.Bq - becquerel
  • si.Gy - gray
  • si.Sv - sievert
  • si.kat - katal

Because the units of si.N are one of the Physical instances that have now been instantiated and loaded into the si namespace, you can perform calculations with them directly:

>>> area = 3*si.m * 4*si.m
>>> force = 2500 * si.N
>>> force / area
>>> 208.333 Pa

Basic usage 2: Top-level namespace

Everything from Basic usage 1 applies, except that, when loading an environment by setting top_level=True, all of the units described in the environment json file will instead be "pushed" into the top-level namespace, i.e. you would not type 5 * si.N but 5 * N.

Basic Usage 2

API

Each Physical instance offers the following methods and properties:

Properties

  • .value: A float that represents the numerical value of the physical quantity in SI base units
  • .dimensions: A Dimensions object (a NamedTuple) that describes the dimension of the quantity as a vector
  • .factor: A float that represents a factor that the value should be multiplied by to linearly scale the quantity into an alternate unit system (e.g. US customary units or UK imperial) that is defined in SI units.
  • .latex: A str that represents the pretty printed repr() of the quanity in latex code.
  • .html: A str that represents the pretty printed repr() of the quantity in HTML code.
  • .repr: A str that represents the traditional machine readable repr() of the quantity: Physical instances default to a pretty printed __repr__() instead of a machine readable __repr__() because it makes them more compatible with other libraries (e.g. numpy, pandas, handcalcs, and jupyter).

Methods

Almost all methods return a new Physical because all instances are immutable.

  • .round(self, n: int): Returns a Physical instance identical to self except with the display precision set to n. You can also call the python built-in round() on the instance to get the same behaviour.
  • .sqrt(self, n: float): Returns a Physical that represents the square root of self. n can be set to any other number to compute alternate roots.
  • .split(self): Returns a 2-tuple where the 0-th element is the .value of the quantity and the 1-th element is the Physical instance with a value set to 1 (i.e. just the dimensional part of the quantity). To reconstitute, multiply the two tuple elements together. This is useful to perform computations in numpy that only accept numerical input (e.g. numpy.linalg.inv()): the value can be computed separately from the dimension and then reconstituted afterwards.
  • .to(self, unit_name: str = ""): Returns a new Physical instance with a .factor corresponding to a dimensionally compatible unit defined in the environment. If .to() is called without any arguments, then a list of available units for that quantity is printed to stdout.
  • .to_dict(self) / Physical.from_dict(data): Converts a Physical to and from a JSON-compatible dict (see Saving quantities to JSON below).

NOTE: float(q) returns the value in the unit that q is displayed in, which depends on its magnitude (float(30.2*si.kN) == 30.2 but float(0.5*si.kN) == 500.0). Use .value (always SI) when you need a stable number.

Parsing quantities from text

Quantities can be parsed from strings, e.g. from YAML or JSON data files, so that units are written once, alongside the data:

>>> si.environment("structural")
>>> si.parse("350 MPa")
350.000 MPa
>>> si.parse("4.5 kN/m")
4.500 kN/m
>>> si.parse("4000 mm")       # a prefixed unit keeps its authored prefix
4000.000 mm
>>> si.parse("164e6 mm**4")   # also "164e6 mm^4" and "164e6 mm⁴"
164000000.000 mm⁴
>>> si.parse("5 kip·ft")      # environment Symbols keep their factor
5.000 kip·ft
>>> si.parse("0.9")           # no units -> float
0.9
>>> si.parse("350 kN", expect="MPa")
DimensionError: Expected the dimensions of MPa (1, -1, -2, 0, 0, 0, 0), got kN (1, 1, -2, 0, 0, 0, 0).
  • Units are environment names (kN), environment symbols (kip·ft, N/m), SI base units, or SI-prefixed SI units (kN·m, μm, mg).
  • A quantity written in a single SI-prefixed unit (0.6 kPa, 4000 mm, 3 μm) displays with that prefix rather than an auto-prefix, so float() of it is in that unit (float(si.parse("0.6 kPa")) == 0.6). .value is always SI (600.0). Compound units (kN/m^3) are auto-prefixed as usual.
  • Combine units with * or ·, /, parentheses and exponents (**, ^ or superscripts). / is left-associative, as in Python (kN/m/s is (kN/m)/s); use parentheses for anything beyond one /.
  • Units separated only by a space ("30 kN m") are rejected as ambiguous.
  • Errors raise si.UnitParseError (a ValueError) with suggestions, e.g. 'kNm' is not a unit in environment 'structural'. Did you mean 'kN·m' (Nm)?
  • There is no eval(): the units are evaluated with a small parser.

si.parse_tree(obj, strict=True) walks nested dicts, lists and tuples (e.g. the result of yaml.safe_load) and parses every quantity string: a number on its own ("12"), or a number followed by whitespace and unit text ("350 MPa"). Keys and other strings are left alone, including strings with something attached directly to the number, such as "W310x74", "2026-10-29", "000.000.000" and "38x140". A quantity string that does not parse ("2 storeys") raises an error naming its path (geometry.levels: '2 storeys'), or is left as a string with strict=False.

Note that "350MPa", without a space, is left as a string by parse_tree (though si.parse("350MPa") accepts it): write a space between the number and its units.

Saving quantities to JSON

>>> q = 30.2 * si.kN
>>> q.to_dict()
{'__physical__': 1, 'value': 30200.0, 'dimensions': [1, 1, -2, 0, 0, 0, 0], 'factor': 1, 'precision': 3, 'prefixed': '', 'environment': 'structural', 'display': '30.200 kN'}
>>> text = si.dumps({"Vr": q, "phi": 0.9})   # also si.dump(obj, fp)
>>> si.loads(text)                           # also si.load(fp)
{'Vr': 30.200 kN, 'phi': 0.9}
  • The round trip is exact: value is always in SI units and a fractional factor (e.g. for ft) is stored exactly as "n/d".
  • Loading does not need an environment. environment (the active environment, omitted if none is loaded) and display are for readers only: si.loads ignores them and never loads an environment.
  • To use the standard library directly: json.dumps(obj, default=si.json_default) and json.loads(text, object_hook=si.json_object_hook).

Quantities in YMPrint projects

With YMPrint 0.8.1 or later installed, forallpeople registers itself as a YMPrint plugin, so there is nothing to configure:

  • A quantity a document exports (_export) or a script publishes is written in the exact JSON form above. Whoever reads it back through _data gets a Physical, not a dict.
  • When a quantity is read back and no environment is active yet, the bundled environment it was written in (its environment) is loaded, so it displays as it was written (16.099 kN/m, not 16099.200 kg·s⁻²). An active environment is never replaced; a different one, or a custom environment that is not bundled, is warned about once.
  • The yaml+units loader reads data files written with units. Every quantity string (a number, alone or followed by a space and units) is parsed as in si.parse_tree; strings like 2026-014 or 000.000.000 are left alone. The file names its environment at the top, either an environment name or a path to an environment .json relative to the file. There is no default environment.
# project.ymprint.yml
_data:
  geometry: {path: geometry.yml, loader: yaml+units}

# geometry.yml
_environment: structural
B01: {span: 6 m, w_DL: 2.5 kN/m, f_y: 350 MPa}

forallpeople has one active environment per process. A data file that names a different environment from the active one replaces it, with a warning.

Dimensionally inconsistent calculations

It is not uncommon for some calculations to use formulas whose dimensions seem to magically appear on their own. The forallpeople library can handle these calculations if the "hidden dimensions" are recognized and accounted for by the user.

Example: in the Canadian concrete design code it is recognized that sqrt(1*MPa) results in units of MPa instead of MPa0.5. Here is one way this can be managed in forallpeople:

>>> import forallpeople as si
>>> from math import sqrt
>>> si.environment('default')
>>> MPa = 1e6 * si.Pa
>>> f_c = 35 * MPa
>>> sqrt(f_c) * MPa
5.916 MPa

This behaviour occurs because of the way __float__ is defined in the Physical class: if float() is called on a Physical, the returned value will be the numerical portion of the auto-reduced, auto-prefixed unit representation.

Example:

>>> import forallpeople as si
>>> from math import sqrt
>>> si.environment('default')
>>> MPa = 1e6 * si.Pa
>>> f_c = 35 * MPa
>>> f_c # As expected
35.000 MPa
>>> float(f_c) # The numerical portion of the prefixed unit
35.0
>>> f_c.value # However, the actual value is 35e6 Pa
35000000.0
>>> sqrt(f_c) # Sqrt of "35"
5.916079783099616
>>> sqrt(f_c.value) # Sqrt of "35000000.0"
5916.079783099616

Many of Python's math functions will first attempt to call float() on an argument that is not already a float. forallpeople takes advantage of this by ensuring the float value returned is the same number you would see in the unit representation. If you prefer the operation be performed on the base unit value, then simply substitute the .value value as the function argument.

How Physical instances work

forallpeople is for describing physical quantities and defines a single class, Physical, to represent them. Physical instances are composed of four components (as attributes):

  • .value: a float that is the numerical value of the quantity in the SI base units.
  • .dimensions: a NamedTuple, called Dimensions, that describes the dimensionality of the physical quantity in terms of the SI base units.
  • .factor: a float that can be used to define a physical quantity in an alternate unit system that is linearly based upon the SI units (e.g. US customary units, imperial, etc.).
  • .precision: an int that describes the number of decimal places to display when the Physical instance is rendered through .__repr__(), default value is 3.
  • .prefixed: a str that represents a prefix abbreviation in the SI units system, e.g. "k" for "kilo", "n" for "nano". This allows the user to over-ride .

Because Physical instances are immutable (just like int, float, str, and bool), the user cannot set these attributes directly. It also means that any arithmetic operation on a Physical instance returns a new instance. Arithmetic operations is the intended way of creating new Physical instances.

Dimension vectors

Physical instances track the dimensions of their physical quantities by using vectors. The vector is stored in the Dimensions class, which is a NamedTuple. Using the vector library, tuplevector (which is "baked in" to forallpeople), vector arithmetic is performed on Dimensions objects directly.

Arithmetic on Physical instancess

Arithmetic on Physical instances work mostly how you would expect, with few caveats:

  • Addition and subtraction:
    • Two (or more) instances will add/sub if dimensions are equal.
    • One instance and one (or more) number(s) (float, int) will add/sub and assume the units of the instance.
    • e.g. a = 5*si.m + 2*si.m, b = 5*si.kg + 10.
  • Multiplication:
    • Instances will multiply with each other and their dimensions will combine.
    • Instances will multiply with numbers and will assume the units of instance(s) that were also a part of the multiplication.
    • e.g. c = 12 *si.m * 2*si.kg * si.s, d = 4.5*si.m * 2.3.
  • Division (true division):
    • Instances will divide by each other and the difference of their dimension vectors will be the dimensions of the new instance.
    • Instances can also divide with numbers and will assume the units of the instance(s) that were also a part of the division.
    • If two instances of the same dimension are divided, the result will be a float (i.e. the units are completely cancelled out; there is no "dimensionless" Physical: either a quantity has units as a Physical or it is a number).
    • e.g. 5 * si.m / (2 * si.m) -> 2.5
  • Floor division:
    • Is intentionally not implemented in Physical. This is because it creates ambiguity when working within an environment where units with factors are defined. (Does floor division return the value of floor division of the SI base unit value or the apparent value after multiplied by it's .factor? Either would return results that may be unexpected.)
    • Floor division can be achieved by using true division and calling int() on the result, although this returns an int and not a Physical instance.
  • Power:
    • You can raise an instance to any power, if it is a number (int, float). You cannot raise a Physical instance to the power of another instance (what would that even mean?).
  • Abs:
    • Returns the absolute value of the instance.
  • Neg:
    • Equivalent to instance * -1.

Auto-prefixing

forallpeople employs "auto-prefixing" and by default selects the most conventional way of representing the unit, scaled to an appropriate prefix.

>>> current = 0.5 * A
>>> current
500.000 mA # 'current' is auto-prefixed to 500 milliamperes
>>> resistance = 1200 * Ohm
>>> resistance
1.200 kΩ # 'resistance' is auto-prefixed to kilo-ohms
>>> voltage = current * resistance
>>> voltage
600.000 V # 'voltage' does not have a prefix because its value is above 1 V but less than 1000 V

The prefixes of the entire SI units system (from 10**-24 to 10**24) are built-in to the Physical class and they step at every three powers of ten (i.e. 10**-3, 10**0, 10**3, 10**6, etc.).

However, auto-prefixing is only triggered in certain, intuitive circumstances:

  1. The unit is one of m, kg, s, A, cd, K, or mol (i.e. the SI base units).
  2. The unit is a derived unit in the SI unit system (i.e. it is defined in the environment and has a .factor == 1).

This means that auto-prefixing is not used in the following circumstances:

  1. The unit is defined in the environment with a factor (e.g. lb: it would not make sense to have a klb or a mlb).
  2. The unit is a compound unit but not defined in the environment (e.g. it would not make sense to have a kkg*m/s).

When the auto-prefixing is triggered for a unit and that unit is of a power other than 1, then auto-prefixing considers the prefix to also be part of the unit's power. For example:

>>> a = 5000 * si.m
>>> a
5.000 km
>>> a**2
25.000 km² # Remember that the 'kilo' prefix is also being squared
>>> b = 500000 * si.m 
>>> b
500.000 km
>>> b**2
250000.000 km² # Why isn't this being shown as 250 Mm²? Because it would take 1,000,000 km² to make a Mm². This is only 250,000 km².

How to define your own environments

NOTE: See the documentation for more information

An environment is simply a JSON document stored within the package folder (or anywhere else: si.environment("path/to/my_units.json") loads an environment from a file path) in the following format:

"Name": {
    "Dimension": [0,0,0,0,0,0,0],
    "Value": 1,
    "Factor": 1,
    "Symbol": ""}

For example, if you wanted to create an environment that defined only kilopascals and pounds-force in US customary units, you would do it like this:

"kPa": {
    "Dimension": [1,-1,-2,0,0,0,0],
    "Value": 1000},
"lb-f": {
    "Dimension": [1, 1, -2, 0, 0, 0, 0],
    "Factor": "1/0.45359237/9.80665",
    "Symbol": "lb"}

Note also that arithmetical expressions in "Factor" are eval'd to allow for the most accurate input of factors; to prevent a security risk, "Factor" is regex'd to ensure that only numbers and arithmetic symbols are in "Factor" and not any alphabetic characters (see Environment._load_environment in source code to validate).

REPLs and Jupyter Notebook/Lab

forallpeople prioritizes usage conventions over Python conventions. Specifically, the library deliberately switches the intentions behind the __repr__() and __str__() methods: __repr__() will give the pretty printed version and __str__() will return the same. As such, it becomes intuitive to use within any Python REPL and it really shines when used in a Jupyter Notebook, where HTML representations are the default. This also makes it nicer to use with Python libraries such as pandas and numpy.

Using Physicals with Numpy

Physical instances can be used with many numpy operations. See below example:

>>> a = 5 * si.kN
>>> b = 3.5 * si.kN
>>> c = 7.7 * si.kN
>>> d = 6.6 * si.kN
>>> m1 = np.matrix([[a, b], [b, a]])
>>> m2 = np.matrix([[c, d], [d, c]])
>>> m1
matrix([
[5.000 kN, 3.500 kN],
[3.500 kN, 5.000 kN]], dtype=object)
>>> m2
matrix([
[7.700 kN, 6.600 kN],
[6.600 kN, 7.700 kN]], dtype=object)
>>> m1 + m2
matrix([
[12.700 kN, 10.100 kN],
[10.100 kN, 12.700 kN]], dtype=object)
>>> m1 @ m2
matrix([
[61.600 kN², 59.950 kN²],
[59.950 kN², 61.600 kN²]], dtype=object)
>>> m2 - m1
matrix([
[2.700 kN, 3.100 kN],
[3.100 kN, 2.700 kN]], dtype=object)
>>> m1 / m2
matrix([
[0.6493506493506493, 0.5303030303030303],
[0.5303030303030303, 0.6493506493506493]], dtype=object)

Documentation

For more detailed information, visit the documentation

PyPI

This package is available on PyPI

Metadata

Release files for forallpeople 3.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for forallpeople 3.3.0
File Size Uploaded Provenance Actions
forallpeople-3.3.0.tar.gz 61.8 kB Without provenance Details for forallpeople-3.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for forallpeople 3.3.0
File Interpreter ABI Platform Actions
forallpeople-3.3.0-py2.py3-none-any.whl Python 2, Python 3 none any Details for forallpeople-3.3.0-py2.py3-none-any.whl

Total release size: 129.7 kB

Release files / forallpeople-3.3.0.tar.gz

Download URL forallpeople-3.3.0.tar.gz
Size 61.8 kB
Tags Source
SHA-256 checksum
How to use checksums
5a37622bb06bb83406e54d1bd7c7ed0f4b40ca95ad570dcc733a040cd0a23570
BLAKE2b-256 checksum
How to use checksums
d9e48e1c0d62987217ea8fa13cf7841d0ffc4fd80c41132042594c7c77c9fc12
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / forallpeople-3.3.0-py2.py3-none-any.whl

Download URL forallpeople-3.3.0-py2.py3-none-any.whl
Size 67.8 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
5ec60b18b4f8e7f5176ee336a0a3cb1fc80c8e9477f467ecacf6a098fc300f80
BLAKE2b-256 checksum
How to use checksums
d9cacf98f1dcb3bdfa3ea152888c02e66151dda5232e17ca922cf8e93f099b43
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for forallpeople 3.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

3.3.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page