On Thu, 2 Nov 2017 10:13 am, Jason Maldonis wrote: > Hi everyone, > > I want to use a metaclass to override how class instantiation works. I've > done something analogous to using the Singleton metaclass from the Python3 > Cookbook example.
In my opinion, nine times out of ten, using a metaclass for something like that is overkill. (And that's putting aside the fact that 999 out of a thousand, using a Singleton is the wrong solution, no matter what the question is.) > However, I want to provide a classmethod that allows for "normal" class > instantiation that prevents this metaclass from being used. To me, that strongly suggests that a metaclass is the wrong solution. > To do that, I think I just make a @classmethod constructor function. > However, I can imagine a few different ways of writing this: > > @classmethod > def normal_constructor(cls, *args, **kwargs): > return type.__call__(*args, **kwargs) Untested, but I think that should be: return type.__call__(cls, *args, **kwargs) > @classmethod > def normal_constructor(cls, *args, **kwargs): > return super(???).__call__(*args, **kwargs) # I'm not sure what should > go in the super here (I'm using python3) > > @classmethod > def normal_constructor(cls, *args, **kwargs): > self = cls.__new__(cls) > self.__init__(*args, **kwargs) > return self > > Is one of these correct? Or do they all do the same thing? None of them look "correct", they all look "weird and scary" :-) If I had to pick one of these three -- and I hope that I would not -- I'd pick the first one. > I was looking for documentation for what exactly `type.__call__` does so > that I can emulate it, And then if type.__call__ changes, your emulation will be wrong. > but I wasn't able to find any docs explicitly > detailing what that method does. If someone knows where this info is that > would be great too. -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list