News for hackers. Stuff that matters.
Re:Please put units in names by nuccy on Monday March 21, 2022 @05:44AM (#30752097)
Speaking of astropy units. I had a hilarious issue last week, which was quite hard to identify (simplified code to reproduce):

  from astropy import units as u
  a = 3 * u.s
  b = 2 * u.s
  c = 1 * u.s
  d = 4 * u.s
  m = min([a, b, c, d])
  a -= m
  b -= m
  c -= m
  d -= m
  print(a,b,c,d)
Output: 2.0 s 1.0 s 0.0 s 4.0 s

Note the last 4.0, while min value is 1.0

The issue is that a, b, c, d are objects when astropy units are applied and min (or max) returns not the value but an object with the minimal value, thus m is c (in this particular case c has the smallest value) so c -= m makes m = 0, so d remains unchanged. It was very hard to spot especially when values change and occasionally either one of a, b, c or d has the smallest value.

In-place augmentation of a working code with units may be very tricky and can create unexpected bugs.

Re:Please put units in names by DiogenesKynikos on Monday March 21, 2022 @08:40AM (#30753384)
This is really an issue with Python in general (specifically, mutable types).

You'd get the exact same behavior with numpy ndarrays (of which astropy Quantities are a subclass).

Re:Please put units in names by dragonwriter on Monday March 21, 2022 @12:05PM (#30755690)
> This is really an issue with Python in general (specifically, mutable types).

Unit-aware values as a type where assignment as mutation is an odd choice though (normal mutable types do not exhibit this behavior, it’s a whole separate behavior which has to be deliberately implemented.) It may make sense in the expected use case (and as you note reflects the behavior of the underlying type), but more generally it's not what someone wanting unit-aware values would probably expect.

Re:Please put units in names by necovek on Monday March 21, 2022 @07:25AM (#30752728)
That sounds like a bug in astropy type definitions: did you get a chance to report it as one?

While it can sometimes be undefined behavior (a minimum of incompatible units), in cases like these it should DTRT.

Re:Please put units in names by deepsun on Tuesday March 22, 2022 @04:26AM (#30763824)
Mutable types are hard.