Anonymous Classes

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Jul 12 04:53:59 EDT 2007


Lachlan Gunn a écrit :
> Hello.
> 
> I have a library (SQLObject) that stores data as class variables.  I would
> like to set a class variable in a certain context, specific to a certain
> instance of an object.  This would require some sort of anonymous class.  I
> have attempted to use the following code to set the connection string:
> 
> | class SQLStorage:

You probably want:

     class SQLStorage(object):

> |    def __init__(self, c, debug = False):
> |        config = StorageConfiguration(c)
> | 
> |        connection = sqlobject.connectionForURI(config.databaseString)
> |        if debug:
> |            connection.debug = True
> | 
> |        # I don't know whether this is right.  My belief is that we can
> |        # subclass each table and use _connection on them.
> |        class newDatum(DatumTable):
> |            _connection = connection
> | 
> |        class newMetadatum(MetadatumTable):
> |            _connection = connection
> | 
> |        class newChecksum(ChecksumTable):
> |            _connection = connection
> | 
> |        self.__SQLDatum     = newDatum
> |        self.__SQLMetadatum = newMetadatum
> |        self.__SQLChecksum  = newChecksum

Are you sure you need name mangling here ?

> This does not work; Python complains that the classes already exist when
> SQLObject is instantiated for a second time.  This has led me to try
> instantiating a subclass using DatumTable.__class__ and friends, but this
> requires setting a class name, which, again, limits me to a single
> instance.  I *could* have a counter that appends a number to each class
> name, but that's a fairly ugly solution; is it possible to create an
> anonymous class in Python?

Yes. Using type() :

Help on class type in module __builtin__:

class type(object)
  |  type(object) -> the object's type
  |  type(name, bases, dict) -> a new type


 >>> class Toto(object):
...     pass
...
 >>> class Tutu(object):
...     def __init__(self, what):
...             self._toto = type('Autototo', (Toto,), dict(_what=what))
...
 >>> t = Tutu(42)
 >>> t._toto
<class '__main__.Autototo'>
 >>> t._toto._what
42
 >>> t._toto()
<__main__.Autototo object at 0xb7c3806c>
 >>> t2 = Tutu(1138)
 >>> t2._toto
<class '__main__.Autototo'>
 >>> t2._toto._what
1138



More information about the Python-list mailing list