Skip to content

Instantly share code, notes, and snippets.

@rec
Created February 26, 2014 20:20
Show Gist options
  • Save rec/9237674 to your computer and use it in GitHub Desktop.
Save rec/9237674 to your computer and use it in GitHub Desktop.
An antipattern using the pint unit representation system.
from pint import UnitRegistry
ureg = UnitRegistry()
x = [ureg['1m'], ureg['1m'], ureg['1m']]
y = [ureg['1m']] * 3
try:
print(sum(y))
except:
# pint.unit.DimensionalityError: Cannot convert from 'meter' to 'dimensionless'
pass
# Oops! OK, so...
def summer(values):
if not values:
return 0
total = values[0]
for v in values[1:]:
total += v
return total
print(summer(x))
# 3 meter Good, it works...
print(summer(y))
# 4 meter Huh?
print(x)
# [<Quantity(3, 'meter')>, <Quantity(1, 'meter')>, <Quantity(1, 'meter')>]
print(y)
# [<Quantity(4, 'meter')>, <Quantity(4, 'meter')>, <Quantity(4, 'meter')>]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment