Search code examples
pythonpython-decorators

apply decorator to a class attribute only


not sure if it's possible, but I would like to replicate the idea of @annotations from java in a python class. The goal would be to iterate through all attributes in this class and return those that are "marked" with a custom decorator (e.g. @render). So, in this case, I can define a generic function that renders a generic UI/view template to display only the render attributes from any class.

In this imaginary code, the Item class would be:

class Item:
    def __init__(self):
        self.id = 100
        @render
        self.desc = 'info about'
        @render
        self.title = 'product x'
        self.vender_ref = 'af2k102hv813'

and only title and desc would be shown/returned. What would be the way to achieve this feature? probably I'm way too far from pythonic thinking here, so appreciate any ideas.


Solution

  • I don't think it's possible to decorate attributes the way you are doing it here. One solution could be this.

    class Item:
        def __init__(self):
            self.id = 100
            self.desc = "info about"
            self.title = "product x"
            self.vender_ref = "af2k102hv813"
            self.__rendered_attributes__ = ["desc", "title"]
    
    
    def render_item(i):
        for attribute in i.__rendered_attributes__:
            value = getattr(i, attribute)
            print("attr", attribute, "=", value)
    
    
    i = Item()
    render_item(i)