Steven D'Aprano a écrit :
<nitpick>
Err... A possible design smell ?-)
</nitpick>
More seriously: this looks quite like a singleton, which in Python is
usually implemented way more simply using a module and plain functions.
I really don't know why everyone thinks I want a Singleton. I want to
uncouple objects, not increase the coupling.
Consider a factory function:
def factory(x): # a toy example
alist = [x]
def foo():
return alist
return foo
Now suppose we "instantiate" the factory (for lack of a better term):
Even though f1 and f2 have the same behaviour, they are obviously not the
same object. And although both return a list [0], it is not the same list:
f1() == f2() == [0] True
f1() is f2()
False
They have a (very little) amount of state, which is *not* shared:
L = f1()
L.append(1)
f1() [0, 1]
f2()
[0]
But there's only a limited amount of state that functions carry around. I
can give them more state like this:
but it isn't good enough if the function needs to refer to it's own
state, because functions can only refer to themselves by name and the
factory can't know what name the function will be bound to.
As far as I know, the only objects that know how to refer to themselves
no matter what name they have are classes and instances. And instances
share at least some state, by virtue of having the same class.
(Pedants will argue that classes also share state, by virtue of having
the same metaclass. Maybe so, but that's at a deep enough level that I
don't care.)
I'm now leaning towards just having factory() instantiate the class and
return the instance, instead of having to do metaclass chicanery. Because
the class is built anew each time by the factory, two such instances
aren't actually sharing the same class. I think that will reduce
confusion all round (including mine!).
Hopefully now that I've explained what I want in more detail, it won't
seem so bizarre. Factory functions do it all the time. Is there a name
for this pattern?
Thanks to everyone who commented, your comments helped me reason out a
better alternative to what I first suggested.