Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
decorator
#1
Hi

I've come up with a use of decorators which I haven't seen anyone else use as of yet, and I'm wondering if there is a reason not to do this. Basically the methods using the decorator are there purely for the method name. I've done this as it allows me to have a general function, but control which columns are available outside the class.

Here is the code for the class with the decorator (__set_field__). The sending record is kept in a table in an sqlite DB, hence the conn parameter.

What I'm after is whether this is good or bad as far as python goes, I'm an experienced scripter, but this is only the 2nd python script I've worked on.

class SendingRecord:
    def __init__(self, conn, processingid, file, destination):
        """ Constructor method """
        self.id = conn.add_sending_record(processingid, file, destination)
        self.processingid = processingid
        self.file = file
        self.destination = destination
        self.send_attempts = 0
        self.last_result = None

    def __set_field__(func):
        @wraps(func)
        def decorator(self, conn, value):
            col_name = func.__name__[4:]
            conn.execute('UPDATE sending SET {0} = ? WHERE id = ?'.format(col_name), (value, self.id))
            conn.commit()
            setattr(self, col_name, value)
        return decorator

    @__set_field__
    def set_status(self, conn, value):
        conn.set_record_status('sending', self.id, status)

    @__set_field__
    def set_send_attempts(self, conn, value):
        pass
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  the order of running code in a decorator function akbarza 2 480 Nov-10-2023, 08:09 AM
Last Post: akbarza
  Curious about decorator syntax rjdegraff42 14 1,977 May-03-2023, 01:21 PM
Last Post: rjdegraff42
  ABC Module and @property decorator, Pythonic Way? muzikman 21 5,496 Aug-18-2021, 06:08 PM
Last Post: muzikman
  Use of @property decorator ruy 16 6,378 Jun-09-2020, 05:29 PM
Last Post: buran
  Decorator staticmethod Use Cases Devarishi 3 2,599 May-20-2019, 04:27 AM
Last Post: Devarishi
  How can we override decorator? bhojendra 2 9,260 May-12-2019, 11:15 PM
Last Post: ichabod801
  Decorator question Dan741 1 2,358 Nov-14-2018, 10:05 AM
Last Post: wavic
  Decorator toy code throws syntax errors kevinxhi 3 3,520 Sep-04-2017, 03:01 AM
Last Post: kevinxhi
  accessing variables from a decorator ashwin 1 3,079 Jun-30-2017, 04:11 PM
Last Post: nilamo
  how to make class and instance method (multiple decorator) ? harun2525 7 5,947 May-29-2017, 04:56 PM
Last Post: harun2525

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020