2

In the source code of Stable Baselines3, in common/preprocessing.py, on line 158, there is: return (int(len(observation_space.nvec)),).

As far as I know, in Python, len can only return an int, and regardless if this is not true, would return an int here (might be wrong on both counts). If this is the case, the cast to int would not make sense to me.

Am I missing something here?

David Cian
  • 541
  • 1
  • 6
  • 16
  • 2
    `len` can only return an int, yeah. If `observation_space.nvec.__len__` returned a non-int, [you'd get an error](/a/59604139/4518341). I don't think you're missing anything. – wjandrea Aug 14 '23 at 19:31
  • 1
    Just a terminology sidenote, `int(...)` isn't really a cast. It's just an ordinary function call. And arguably casting has a different meaning in Python, i.e. `cast(int, ...)` – Brian61354270 Aug 14 '23 at 19:37

1 Answers1

3

The call to int is not necessary.

len always returns an int. If a class' __len__ implemention returns something other than an int, Python will attempt to convert it to an int. If that can't be done, a TypeError will be raised. There's no scenario where len can return something other than an int.

You can try to violate this yourself:

class Foo:
    def __len__(self):
        return "bad"

>>> len(Foo())
Traceback (most recent call last)
...
TypeError: 'str' object cannot be interpreted as an integer
Brian61354270
  • 8,690
  • 4
  • 21
  • 43