2021-01-14 Paul Sokolovsky <[email protected]> dixit:
> 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.
[...]
> 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).
[...]
I suppose it could be something along the lines (warning: not tested):
REOPEN_DEFAULT_IGNORED_ATTRS = frozenset({
'__dict__',
'__doc__',
'__module__',
'__weakref__',
})
def reopen(cls, ignored_attrs=REOPEN_DEFAULT_IGNORED_ATTRS):
def decorator(mixin):
for name, obj in vars(mixin).items():
if name not in ignored_attrs:
setattr(cls, name, obj)
return decorator
Then it could be used, for example, in the following way:
@reopen(MyClass)
class _:
def my_additional_method(self, foo, bar):
...
Cheers.
*j
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/SDBOJGNCHIP5VRBYHVM6SKUU4IF4H5AH/
Code of Conduct: http://python.org/psf/codeofconduct/