Hello,

Ruby has following feature. Suppose the existing class "Cls" is scope
(either defined before or imported from some module), then the code
like:

class Cls
    def mixin_method(args)
        ...
    end
end

Will "reopen" (Ruby term) that class and will add a new method
"mixin_method" to it.

Syntactically, that's complete madness - the same syntax is used to
both define the class initially and augment it afterwards, and that's
expectedly leads to user confusion, e.g.
https://stackoverflow.com/questions/4464629/ruby-rails-reopening-vs-overwriting-a-class

Semantically, Python can achieve the same with "imperative" syntax like:

def mixin_method(self, args):
    ...
Cls.mixin_method = mixin_method


The question then: what are the best practices in *declarative* syntax
to achieve the same effect in Python? (but of course, unlike Ruby,
there should be explicit syntactic marker that we augment existing
class, not redefine it).

One of usecases should be clear from the example above - it's an easy
way to add a mixin to the class, without relying on multiple inheritance
(which has many its own problems). It's also emerging
language-flexibility/expressivity best practice to be able to define
interfaces on classes (types) post-factum. Such interfaces are called
different buzzwords in different languages, e.g. Haskell calls them
"typeclasses" and Rust calls them "traits". The question is again how
do we syntactically encode it in Python (with a hint that the matter
is rather similar to post-factum mixing-in).


-- 
Best regards,
 Paul                          mailto:pmis...@gmail.com
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/VMJRDKMIJEYGB7JRDT4BBSIKFL6KMGKH/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to