Search code examples
pythonclassinstancedecorator

ways to return an updated instance of a class python


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

Solution

  • class CLS:
    _instance = None
    .....
    
    def __new__(cls, *args, **kwargs):
        cls._instance = super().__new__(cls)
        return cls._instance
    

    and

    connection = cls._instance.connection
    

    its work