Named integers and enums

Shalabh Chaturvedi shalabh at cafepy.com
Sun May 23 18:20:48 EDT 2004


Hallvard B Furuseth wrote:
> Is this possible without too much code?
> 
>     class Named_int(object, int):

It is not be possible inherit from object and int in this order. When I 
try it in 2.3, I get a TypeError. Why do you want to subclass object 
here anyway? int is already a subclass of object, so just Named_int(int) 
should be enough.

>         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".

As others have answered, you need __new__ instead of __init__.

<alternative example snipped>

> 
> 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)
> 

If you don't care about the int values (but I suspect you do :), and 
need pure enums, one option is to just use plain and simple objects:

Debug = object()
Info = object()
etc.

HTH,
Shalabh





More information about the Python-list mailing list