Created
February 26, 2014 20:20
-
-
Save rec/9237674 to your computer and use it in GitHub Desktop.
An antipattern using the pint unit representation system.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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