confused about __new__

Ian Kelly ian.g.kelly at gmail.com
Tue Dec 27 13:28:42 EST 2011


On Tue, Dec 27, 2011 at 10:41 AM, K Richard Pixley <rich at noir.com> wrote:
> The conceptual leap for me was in recognizing that a class is just an
> object.  The best way, (imo, so far), to create a singleton in python is to
> use the class itself as the singleton rather than ever instantiating it.
>  With a little work, you can even prevent it from ever being instantiated.

I don't think that's actually possible:

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     def __new__(cls):
...         raise TypeError
...     def __init__(self):
...         raise TypeError
...
>>> type(object.__new__(Foo))
<class '__main__.Foo'>

I prefer the Borg pattern for singletons myself.  When you need a Borg
instance, you just instantiate the class normally, do whatever you
need with it, and then discard it normally.  It doesn't matter how
many instances there are (there can even be zero) because they all
share identical state.  It's better encapsulation too, since client
code does not even need to know that the class is a singleton variant;
that becomes an implementation detail.

http://www.aleax.it/Python/5ep.html
http://code.activestate.com/recipes/66531/


> But __metaclass__ could use a few more examples, imo.  I'm still not
> entirely clear on __metaclass__.  As I understand it, (which may well be
> completely wrong), __metaclass_ is the means of perturbing the results of
> "isinstance".  You can create, (or delete), inheritance arbitrarily, and
> without even requiring real, existing classes to do it.

A metaclass is the class of another class (which is normally `type` if
no metaclass is specified).  It's used to customize the way that the
class is created, in the same way that the class can be used to
customize the way instances are created (e.g. by overriding __new__).
You could use it to mess with the class's base classes, although I
think that usage is rare.  It's more common to use it to automatically
add or modify entries in the class dict.  For example, Django models
use a metaclass to collect all the fields and options declared for the
model class and to setup a default manager for the model class.

Note that many things that can be done with a metaclass can also be
done with a class decorator.  The main difference as I see it is that
the metaclass is inherited by subclasses, whereas a decorator would
need to be applied individually to each subclass.



More information about the Python-list mailing list