[Python-ideas] Composition over Inheritance

Thomas Jollans tjol at tjol.eu
Mon Oct 30 04:38:16 EDT 2017

On 29/10/17 19:25, Soni L. wrote:
> On 2017-10-29 02:57 PM, Brendan Barnwell wrote:
>> On 2017-10-29 04:44, Soni L. wrote:
>>> And this is how you miss the whole point of being able to dynamically
>>> add/remove arbitrary components on objects you didn't create, at
>>> runtime.
>>> Someone gave me this code and told me it explains what I'm trying to do:
>>> https://repl.it/NYCF/3
>>> class T:
>>>      pass
>>> class C:
>>>      pass
>>> c = C()
>>> #c.[T] = 1
>>> c.__dict__[T] = 1
>>     Again, can you please explain why you want to write c.[T]? What do
>> you intend that to *do*?  Your commented line seems to indicate you
>> want it to do what `c.__dict__[T]` does, but you can already do that
>> with `setattr(c, T, 1)`.  Or you can just give c an attribute that's a
>> dict, but has an easier-to-type name than __dict__, so you can do
>> `c.mydict[T]`.  What is the specific advantage of `c.[T]` over these
>> existing solutions?
> Hmm... Why can't we just allow empty identifiers, and set a default
> handler for empty identifiers that implements the proposed ECS?

It sounds to me like the general shape of what you're proposing is
already entirely possible, just without the idiosyncratic syntax. You
could write a library that adds support for your components using some
other syntax without any additional language support.

I don't know, something like this should be doable:

class Car:
    # ...

class Engine(componentlib.Component): # might have to be a metaclass?
    def stall(self, car):
        raise UnpleasantNoise()
    # ...

car = Car()
car.engine = Engine()
# and so on.

If you prefer square brackets, you can implement it with __getitem__
syntax instead of __getattr__ syntax.

The point is: not only does your proposal not *need* additional language
support; I'm not at all convinced that it would benefit from additional
language support.

> But the basic idea is to indicate something at the call site, namely
> that T is a contract and the object returned should respect that
> contract and any function calls should pass the original object as an
> argument. (I personally don't like how Python treats o.m() (has self)
> the same as o.f() (no self) syntax-wise, either.)
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/

More information about the Python-ideas mailing list