[Python-ideas] An even simpler customization of class creation
Steven D'Aprano
steve at pearwood.info
Mon Mar 2 12:46:59 CET 2015
On Mon, Mar 02, 2015 at 11:57:09AM +0100, Martin Teichmann wrote:
> Imagine a soliton-generating metaclass:
>
> class Soliton(type):
> def __new__(cls, name, bases, ns):
> self = super().__new__(name, bases, ns)
> return self()
You have to pass cls as an explicit argument to __new__, otherwise you
get a TypeError:
TypeError: type.__new__(X): X is not a type object (str)
(that's in Python 3.3). The line should be:
self = super().__new__(cls, name, bases, ns)
> And generate such a soliton:
>
> class A(metaclass=Soliton):
> def f(self):
> print(__class__)
>
> As of now, writing "A.f()" interestingly prints "<__main__.A object>", so
> __class__ is indeed set to what Soliton.__new__ returns, the object,
> not the class.
Is "soliton" the usual terminology for this? Do you perhaps mean
singleton? I've googled for "soliton" but nothing relevant is coming up.
> This is currently correct behavior, but I think it actually is not what one
> expects, nor what one desires. (Does anyone out there make use of
> such a construct? Please speak up!)
I do now! Seriously, I think you have just solved a major problem for
me. I'll need to do some further experimentation, but that is almost
exactly what I have been looking for. I've been looking for a way to
have a class statement return a custom instance and I think this might
just do it.
--
Steve
More information about the Python-ideas
mailing list