[Python-Dev] Octal literals
Nick Coghlan
ncoghlan at gmail.com
Fri Feb 3 12:15:22 CET 2006
Bob Ippolito wrote:
>
> On Feb 3, 2006, at 2:07 AM, Nick Coghlan wrote:
>> Currently, there is no syntax for binary literals, and the syntax for
>> octal
>> literals is both magical (where else in integer mathematics does a
>> leading
>> zero matter?) and somewhat error prone (int and eval will give different
>> answers for a numeric literal with a leading zero - int ignores the
>> leading
>> zero, eval treats it as signifying that the value is in octal. The
>> charming
>> result is that the following statement fails: assert int('0123') ==
>> 0123).
>
> That's just a misunderstanding on your part. The default radix is 10,
> not DWIM. 0 signifies that behavior::
>
> assert int('0123', 0) == 0123
> assert int('0x123', 0) == 0x123
How does that make the situation any better? The fact remains that a leading
zero on an integer string may be significant, depending on the exact method
used to convert the string to a number. The fact that int() can be made to
behave like eval() doesn't change the fact that the default behaviours are
different, and in a fashion that allows errors to pass silently.
You've highlighted a nice way to turn this into a real bug, though - use the
DWIM feature of int() to accept numbers in either decimal or hex, and wait
until someone relying on the mathematics they learned in high school enters a
decimal number with a leading zero (leading zeros don't matter, right?).
I think it's a bad thing that Python defaults to handling numbers differently
from high school mathematics. One of the virtues of '0x' and '0o' is that the
resulting strings aren't actually legal numbers, leading to people wondering
what the prefixes mean. The danger of the leading 0 denoting octal is that
programmers without a background in C (or one of its successors that use the
same convention) may *think* they know what it means, only to discover they're
wrong the hard way (when their program doesn't work right).
Do I think this *really* matters? Nope - I think most bugs due to this will be
pretty shallow. That's why I was only +0 on doing anything about it.
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-Dev
mailing list