raysect / source

The main source repository for the Raysect project.
http://www.raysect.org
BSD 3-Clause "New" or "Revised" License
86 stars 23 forks source link

Assigning to spectrum.samples breaks spectrum integrity #402

Closed vsnever closed 2 years ago

vsnever commented 2 years ago

The attribute samples is a public attribute of the Spectrum class, thus it is possible to directly assign the value to this attribute without safety checks. The following code breaks the integrity of the spectrum object because the sample length becomes inconsistent with the number of spectral bins, and the memoryview spectrum.samples_mv no longer points to the spectrum.samples buffer.

import numpy as np
from raysect.optical import Spectrum

spectrum = Spectrum(300, 500, 200)
spectrum.samples = np.ones(100)
print(spectrum.bins)

I suggest making samples a property because in this case any direct assignments spectrum.samples = new_samples in the user code will continue to work.

An alternative solution would be making samples a read-only attribute. In this case, the users must replace spectrum.samples = new_samples with spectrum.samples[:] = new_samples in their code.

@CnlPepper, I can make a patch. What is the best solution in your opinion?

CnlPepper commented 2 years ago

Curious, it should have been readonly! I'll fix it now.