kdavies4 / natu

Natural units in Python
http://kdavies4.github.io/natu/
Other
33 stars 5 forks source link

homogeneous_copy_props_iter doesn't work with generators #37

Open iangoldby opened 6 years ago

iangoldby commented 6 years ago

You can't use math.fsum() with a generator:

from natu.units import m
import natu.math as math
x = (r * m for r in range(10))
y = math.fsum(x)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Ian\AppData\Local\conda\conda\envs\sandpit\lib\site-packages\natu-0.1.2-py3.6.egg\natu\_decorators.py", line 248, in wrapped
    return merge(func(map(value, x)), x[0])
TypeError: 'generator' object is not subscriptable

Inside the decorator homogeneous_copy_props_iter() there are two problems:

  1. assert_homogeneous(*x) exhausts the generator.
  2. merge(func(map(value, x)), x[0]) tries to reference an element by index.

I don't think the correct fix is to realise the generator as a list because most of the reason generators are used is so that the entire sequence does not have to be held in memory in one go.