[Python-ideas] Enums
Robert Kern
robert.kern at gmail.com
Mon Jul 25 23:44:56 CEST 2011
On 7/25/11 4:39 PM, Michael Foord wrote:
>
>
> On 25 July 2011 21:47, Robert Kern <robert.kern at gmail.com
> <mailto:robert.kern at gmail.com>> wrote:
>
> On 7/25/11 1:43 PM, Michael Foord wrote:
>
> Some apis (for example those exported directly from C) can't work with
> something
> that isn't a real int.
>
>
> I think almost all of those will usually accept an object that implements
> __int__ and __index__, don't they? E.g.
>
> [~]
> |1> import os
>
> [~]
> |2> class A(object):
> ..> def __init__(self,x):
> ..> self.x = x
> ..> def __int__(self):
> ..> return self.x
> ..> def __index__(self):
> ..> return self.x
> ..>
>
> [~]
> |10> os.open('foo', A(os.O_RDWR))
> 21
>
>
> os.open() just uses PyArg_ParseTuple(), like most extension functions. I'm
> sure you could write an extension function that would reject A() instances,
> but it's more work, so most people don't.
>
>
> Providing __index__ may indeed be enough.
From experiment with os.open() under 2.7 and 3.1, it is not enough, though
perhaps either PyArg_ParseTuple() or PyInt_As*() should be modified to make it so.
--
Robert Kern
"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco
More information about the Python-ideas
mailing list