Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #24840

Re: Dictless classes

From Terry Reedy <tjreedy@udel.edu>
Subject Re: Dictless classes
Date 2012-07-03 19:25 -0400
References <4ff27d28$0$11103$c3e8da3@news.astraweb.com>
Newsgroups comp.lang.python
Message-ID <mailman.1767.1341357962.4697.python-list@python.org> (permalink)

Show all headers | View raw


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


Back to comp.lang.python | Previous | NextPrevious in thread | Find similar | Unroll thread


Thread

Dictless classes Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-07-03 05:03 +0000
  Re: Dictless classes alex23 <wuwei23@gmail.com> - 2012-07-02 22:50 -0700
  Re: Dictless classes Duncan Booth <duncan.booth@invalid.invalid> - 2012-07-03 09:38 +0000
    Re: Dictless classes Roy Smith <roy@panix.com> - 2012-07-03 08:28 -0400
  Re: Dictless classes Terry Reedy <tjreedy@udel.edu> - 2012-07-03 19:25 -0400

csiph-web