Named integers and enums

Hallvard B Furuseth h.b.furuseth at usit.uio.no
Sun May 23 16:48:08 EDT 2004


Is this possible without too much code?

    class Named_int(object, int):
        def __str__(self): return self.name
        __repr__ = __str__
        __slots__ = 'name'
        # This does not work:
        def __init__(self, name): self.name = name
        # ...and it would be nice to freeze the name:
        __setattr__ = __delattr__ = None

    x = Named_int(3, "foo")
    print "%s = %d" % (x, x) # print "foo = 3"

Named_int(3, "foo") says "TypeError: an integer is required".
I've tried other ways to specify both parameters, but no luck so far.
BTW, this is Python2.2.  I don't know if we'll be able to upgrade
anytime soon.

I know I could do

    class Named_int:
       def __init__(self, val, name):
           self.val, self.name = int(val), str(name)
       ...

but then I'd need a bunch of other functions: __int__, __cmp__,
__nonzero__, __hash__, maybe also __add__ and so on.

Or is there another way?  Currently I'm only planning to use it for is a
C-style enum, so it's merely a bit irritating that I have to set the
name attribute after creating the Named_int:

    import sys

    class Named_int(object, int):
        def __str__(self): return self.name
        __repr__ = __str__
        __slots__ = 'name'

    def Enum(**mapping):
        vars = sys._getframe(1).f_locals
        for name, val in mapping.items():
            val = Named_int(val)
            val.name = name
            vars[name] = val

    Enum(
        Debug = 0,
        Info = 1,
        Warning = 2,
        Error = 3,
        Critical = 4
        )

    # print "Error = 3"
    print "%s = %d" % (Error, Error)

-- 
Hallvard



More information about the Python-list mailing list