Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why cast return value of len to int in Python?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading