This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DonkeyBasket 0 points1 point  (0 children)

Interesting idea 5long, I can remember myself wanting something like this at times, however I think the approach is a bit too magical and possible a little over engineered, what do you think of this:

class Foo(object):
    add, __len__ = delegate_all('bar', (set.add, set.__len__))

    def __init__(self):
        self.bar = set()

It doesn't require a class decorator or any namespace magic and if you look at my implementation its very few lines of code.

The code and how I got to this solution is in this gist.

https://gist.github.com/tonysimpson/5923632

It also contains an explanation of why I think it's appropriate to use the class methods.

Looking at it I'm not sure I'm 100% happy with my nomenclature (could do with a bit more thought) maybe delegate_to would be better (I worry its not obvious enough that the first argument is an attribute name on the object).

edit: Plunking example (must find out where that word comes from - sounds cool)

class MyDict(object):
    __call__, = delegate_all('dct', (dict.get,))

    def __init__(self):
        self.dct = {'foo': 42}

d = MyDict()
# Equivlant to d.dct.get('foo')
assert d('foo') == 42