Dictless classes
Terry Reedy
tjreedy at udel.edu
Tue Jul 3 19:25:42 EDT 2012
On 7/3/2012 1:03 AM, Steven D'Aprano wrote:
> You can create instances without a __dict__ by setting __slots__:
Each *instance* does not have its own dict because each would be equal,
therefore only one hidden mapping is needed, somewhere. But attribute
names must be mapped to objects somehow.
> I wonder whether there is some metaclass magic one can do to create a
> class without a __dict__?
If every 'class' instance of the metaclass has the same attributes, then
it would not be necessary for each 'class' to have its individual dict.
But would you call such things 'classes'?
> I don't have a use-case for this. But I have some code which assumes
> that every class will have a __dict__, and I wonder whether that is a
> safe assumption.
It depends what you mean by a class. A 'metaclass' is just a callable
that accepts 3 args. The only constraint appears that its return must be
callable (and accept at least one arg).
class M():
__slots__ = ()
def __init__(*args): pass
def __call__(*args): pass
class C(metaclass = M): pass
c=C()
print(type(C), C, c, hasattr(C, '__dict__'))
#
<class '__main__.M'> <__main__.M object at 0x000000000220A1C0> None False
Is C a dictless class? Your choice ;-).
Actually, Python thinks not. If we add
class Mclassob(object): pass
and have __call__ return an instance thereof and try
c.__class__ = C
we get
TypeError: __class__ must be set to a class, not 'M' object
--
Terry Jan Reedy
More information about the Python-list
mailing list