Interpret "for i in n" as "for i in range(n)" if n is an int

If this was implemented, would for i in True iterate once?

I think it’s better if code like this crashes. Being less strict about inputs is imo a dangerous path. I am against this idea for this reason.

2 Likes

Not sure about the right implementation, but the spirit of this suggestion was for that code to crash, since type(True) is bool, rather than int. It’s true that bool is a subclass of int, so isinstance(True, int) is True, but the recommendation would be for this to only work if the class of the object is int, not for all subclasses of int.

Having it not work for user subclasses of int, specifically designed to be interchangeable with actual integers, seems like it would be an annoying restriction.

To be clear, there’s literally no benefit to this proposal beyond being able to omit range() in for i in range(n) - is that correct?

1 Like

Yes - sole benefit is to omit range().

1 Like

OK, so that’s never going to happen, then. There’s got to be a much bigger benefit than that to justify a language change.

10 Likes

Ah, but if int were to be treated as von Neumann ordinals, now I am greedy. I want nearly all of ZF.

int({0,1,2,3}) == 4  # True
set(4)  # = {0,1,2,3}
set(-4)  # = {-3, -2, -1, 0} Some convention for negatives.
int({0,2,3})  # ValueError. It is currently a TypeError
4 + 1 == int(set(4) | set(set(4)))  # True

I am only joking.

Nice explanation. Thanks.

I hear the objections, but briefly wanted to go back / reverse something I said before. I think subclasses of int should be interchangeable with actual integers for this purpose.

I think that this:

>>> for i in True:

Is not particularly more weird than, and should (under the proposal) be interpreted as this currently is:

>>> for i in range(True):
...     print(i)
...
0

@boxed @pf_moore

2 Likes

I would assume that cases like for _ in range(...): could be pretty trivially optimised by the runtime to not produce values, if the variable is never used.

Not really, there’s no guarantee that range isn’t monkey patched. It wouldn’t be wise nor obvious but the dynamic nature of Python makes it possible to do. It’s maybe possible that the Tier 2 interpreter can do some cool runtime shenanigans but that might not be trivial.