[Python-Dev] str with base

Brett Cannon brett at python.org
Tue Jan 17 07:41:06 CET 2006


On 1/16/06, Guido van Rossum <guido at python.org> wrote:
> On 1/16/06, Alex Martelli <aleaxit at gmail.com> wrote:
> > Is it finally time in Python 2.5 to allow the "obvious" use of, say,
> > str(5,2) to give '101', just the converse of the way int('101',1)
> [I'm sure you meant int('101', 2) here]
> > gives 5?  I'm not sure why str has never allowed this obvious use --
> > any bright beginner assumes it's there and it's awkward to explain
> > why it's not!-).  I'll be happy to propose a patch if the BDFL
> > blesses this, but I don't even think it's worth a PEP... it's an
> > inexplicable though long-standing omission (given the argumentative
> > nature of this crowd I know I'll get pushback, but I still hope the
> > BDFL can Pronounce about it anyway;-).
>
> I wish you had an argument better than "every bright beginner assumes
> it exists". :-)
>
> But (unlike for some other things that bright beginners might assume)
> I don't think there's a deep reason why this couldn't exist.
>
> The only reasons I can come up with is "because input and output are
> notoriously asymmetric in Python" and "because nobody submitted a
> patch". :-)
>
> There are some corner cases to consider though.
>
> - Should repr() support the same convention? I think not.
> - Should str(3.1, n) be allowed? I think not.
> - Should str(x, n) call x.__str__(n)? Neither.
> - Should bases other than 2..36 be considered? I don't think so.
>
> Unfortunately this doesn't obsolete oct() and hex() -- oct(10) returns
> '012', while str(10, 8) soulc return '12'; hex(10) returns '0xa' while
> str(10, 16) would return 'a'.
>
> I do think that before we add this end-user nicety, it's more
> important to implement __index__() in Python 2.5. This behaves like
> __int__() for integral types, but is not defined for float or Decimal.
> Operations that intrinsically require an integral argument, like
> indexing and slicing, should call __index__() on their argument rather
> than __int__(), so as to support non-built-in integral arguments while
> still complaining about float arguments. This is currently implemented
> by explicitly checking for float in a few places, which I find
> repulsing. __index__() won't be requested by bright beginners, but it
> is important e.g. to the Numeric Python folks, who like to implement
> their own integral types but are suffering from that their integers
> aren't usable everywhere.
>

+1 from me (feel like this has come up before, but not totally sure). 
Be nice to add an abstraction for indexing.

Added to the PyCon wiki as a possible sprint topic.

-Brett


More information about the Python-Dev mailing list