[Python-Dev] PEP 318 - posting draft
Alex Martelli
aleaxit at yahoo.com
Wed Mar 24 15:41:05 EST 2004
On Wednesday 24 March 2004 09:01 pm, Skip Montanaro wrote:
> >> class Foo(singleton):
> >> ...
> >> Foo = Foo()
>
> Guido> Ok, so the metaclass would have to be a little different, but
> Guido> this can be done with metaclasses.
>
> I'll take your word for it, but I wouldn't have the faintest idea how to do
> that.
Perhaps something like...:
class metaSingleton(type):
def __new__(cls, classname, classbases, classdict):
result = type.__new__(cls, classname, classbases, classdict)
if classbases:
return result()
else:
return result
class singleton:
__metaclass__ = metaSingleton
class Foo(singleton):
pass
print 'foo is', Foo, 'of type', type(Foo)
which outputs:
foo is <__main__.Foo object at 0x403f968c> of type <class '__main__.Foo'>
...? (As to _why_ one would want such semantics, I dunno -- Singleton being
most definitely _not_ my favourite DP, anyway...:-)
Alex
More information about the Python-Dev
mailing list