Re: [RFC] Define proper semantics for range() function
| From: | Christian Schneider | Date: | Tue, 28 Mar 2023 16:03:46 +0000 |
| Subject: | Re: [RFC] Define proper semantics for range() function | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-119756@lists.php.net to get a copy of this message | ||
Am 28.03.2023 um 14:42 schrieb G. P. B. <george.banyard@gmail.com>:
> On Tue, 28 Mar 2023 at 08:19, Christian Schneider <cschneid@cschneid.com> wrote:
>> There are two cases I would handle differently:
>> - I'm not sure why a negative step for $start > $end is considered wrong, I
>> consider range(10, 0, -2) at least as logical/readable as using a positive decrement of 2. Not
>> requiring a sign for steps seems weirder to me but that's something we cannot change. *BUT* if
>> it is the result of a calculation it seems wrong to require an abs() around it. I do see the reason
>> for a warning/error when $start < $end and $step < 0.
>>
> Considering the only other programming language that I know of that has a range() function that
> accepts a step argument is Python, and its behaviour is IMHO worse.
> For increasing ranges it requires a positive step, and if not just generates an empty range.
> For decreasing ranges it requires a negative step, and if not just generates an empty range (this
> applies even if using the default step value of 1 which is bonkers).
>
> Making it a requirement to pass a negative step is definitely out of the question.
> Making it okay to use negative steps *only* for decreasing ranges could be sensible, but we
> check for the step parameter way before we look into the boundary values because those are different
> for int, float and string boundaries.
> Moreover, I personally find it weirder to require a sign for negative steps as for me a step is
> something that *must* be positive
I quickly checked our own codebase and there is indeed one instance of
range($last, 0, -1)
which was not written by me so there is at least one more person who found this logical ;-)
>> - Values of '' or null in integer context (e.g. range(null, 10, 2)) should IMHO
>> emit a warning first, not directly be changed to a TypeError. The usual BC / migration concern :-)
>
> Trying to figure out if an empty string was used with another string boundary is tedious, as
> this information needs to somehow get carried around.
> A previous iteration of the PR used to convert empty strings to 0 with a warning, but
> considering the analysis I decide to just make this a ValueError as it doesn't seem that empty
> strings are actually used in practice.
> But this is an easy revert, and I'm not really bound to this decision.
Even though this might be a bit cumbersome at the moment I think this would be an important
transition step as currently
range('', 10, 2);
returns the (somewhat) expected result of 0, 2, 4, 6, 8, 10 so I'd be in favor of first giving
a warning and then changing it to a ValueError.
- Chris