More random python observations from a perl programmer

C.Laurence Gonsalves clgonsal at keeshah.penguinpowered.com
Sun Aug 22 18:09:18 EDT 1999


On 19 Aug 1999 08:22:49 -0700, Tom Christiansen <tchrist at mox.perl.com> wrote:
> GOTCHA: (medium)
>     Perl's hex() function is the opposite of Python's.  Perl's hex
>     function converts 22 into 37.  Python's hex function converts 37 into
>     0x22.  Oh my!  Like hex, Python has oct() completely backwards from
>     Perl.  Python's oct(44) returns 054, but Perl's oct(44) return 36.

I'd have to say Python definitely has more sensible meanings for these
functions. Consider the following:

In Perl:
    hex(10)        -> 16
    hex(0x10)      -> 22

Okay, so hex(10) is 10 reinterpreted as hex, but what is hex(0x10)? It's
0x10, converted to decimal (16), and the reinterpreted as hex (0x16 =
22). Huh?

In Python:
    hex(10)        -> '0xa'
    hex(0x10)      -> '0x10'
 
In Python, hex converts a number into a string containing the hex
representation. Much clearer than the rather circuitous meaning of the
Perl hex function...

I suppose the Perl hex function's weird behaviour has to do with the
fact that 'scalars are scalars' in Perl, and numerical quantities are
treated as equivalent to strings containing their decimal
representation. So in Perl, 0x10 == 16 == "16", and the hex function is
really intended to convert strings containing hex quantites into
numbers. It's rather odd that in Perl, 0x10 is equivalent to the string
"16", so passing 0x10 to Perl's hex results in decidely non-intuitive
behaviour.

In Python, if the hex function were to do anything at all like Perl's
(and still be at all useful), it would have to take a string as a
parameter, not a number, in which case you'd be complaining that hex(10)
raised a TypeError. It wouldn't make sense for it to take a number,
because how do you convert a number 'from hex'? That has no meaning,
unless you treat numbers as decimal strings (like Perl does).

In Python, the meaning of hex is also conceptually consistent with
type-conversion functions like int, float, str, etc. In Python,
conversion functions convert *to* what the function names, not from it.

-- 
  C. Laurence Gonsalves            "Any sufficiently advanced
  clgonsal at kami.com                 technology is indistinguishable
  http://www.cryogen.com/clgonsal/  from magic." -- Arthur C. Clarke




More information about the Python-list mailing list