Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #72991

Re: Decorating one method of a class C with another method of class C?

References <CAGGBd_pM5DGp85LVfeQgYwqS8DU8nuQL8Q8G5EzfQ5BX26fa-w@mail.gmail.com> <85lht91s30.fsf@benfinney.id.au> <CAGGBd_qiaw5jahp8QTkc0R+pz3RRvo6c_QTgXZ=ZdrOnvEv++w@mail.gmail.com>
Date 2014-06-09 04:21 +1000
Subject Re: Decorating one method of a class C with another method of class C?
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.10899.1402251682.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Jun 9, 2014 at 4:04 AM, Dan Stromberg <drsalists@gmail.com> wrote:
> I have a class that's operating on a socket.
>
> I'd like to have simple operations on that socket like "list
> configured hosts", "allow connection to host", etc.  And I'd like them
> to be decorated with "reconnected_to_server_if_needed".
>
> I'll probably end up putting a try/except in each simple operation,
> making them a bit less simple.

Can you have the decorator outside the class, calling a regular method
to do its main work?

def recon_if_needed(f):
    def inner(self, *a, **kw):
        if self.disconnected: self.connect()
        return f(self, *a, **kw)
    return inner
class SocketWorker:
    @recon_if_needed
    def send_packet(self, packet):
        assert not self.disconnected

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Decorating one method of a class C with another method of class C? Chris Angelico <rosuav@gmail.com> - 2014-06-09 04:21 +1000

csiph-web