[Python] Descriptor as decorator with variable arguments [duplicate]

Discussão em 'Python' iniciado por Stack, Janeiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    I want to create a @property like feature with serialization capabilities. It would take some arguments. I have created a descriptor like so:

    class CustomMethod:
    def __init__(self, serialize: bool = True):
    self.serialize = serialize

    def __call__(self, func):
    self.func = func
    return self

    def __get__(self, obj, owner):
    if obj == None:
    return self
    f = self.func.__get__(obj, type(obj))
    return f()


    It works when I call it like so:

    @CustomMethod(serialize=True)
    def objects(self):


    or

    @CustomMethod()
    def objects(self):


    But I want to be able to call it without the parenthesis (the serialize arg will get the default value):

    @CustomMethod <-- raises an error
    def objects(self):
    ...


    How to do so?

    Continue reading...

Compartilhe esta Página