Home > Software engineering >  ways to return an updated instance of a class python
ways to return an updated instance of a class python

Time:12-12

it is my simple decorator there is some main() with cls = CLS()

def main():
    ....
    cls = CLS()
    result = func1(cls, some_data)
    >>> new cls Instead of old cls

@decorator
def func1(*, **)

i want to replace old cls to new cls if was exeption in decorator i can use global variable i can use return cls is any more ways to replace ? with out global vars or return

   def decorator(func):
        @wraps(func)
        def wrapper(cls, *args, **kwargs):
            connection = cls.connection
            data = func(*args, **kwargs)
            While True: 
                try:
                    result = connection(data)
                except:
                    cls = CLS()
                    connection = cls1.connection
            return result
      return wraper

CodePudding user response:

Without a return value or a global variable, your only option is to use a wrapper object so that you can change the reference in the decorator. The question is, if you really need to update the CLS or just the connection.

So you could do this instead:

cls.connection = new CLS().connection

The idea remains the same, it just a question whether you need an additional wrapper. The cls in main will have the updated connection.

CodePudding user response:

class CLS:
_instance = None
.....

def __new__(cls, *args, **kwargs):
    cls._instance = super().__new__(cls)
    return cls._instance

and

connection = cls._instance.connection

its work

  • Related