How to override __new__ and handle arguments

  Kiến thức lập trình

I am trying to override MyObject.__new__() in order to verify that it has been called by the MyObject.create() method before creating the instance and returning it and raise an error if it is not. I have to make a seperate create() method because it have to be async and we can’t make __init__() async.

It works fine without arguments, but when i try to add an argument i get the error TypeError: object.__new__() takes exactly one argument (the type to instantiate). Don’t i have to pass the arguments through __new__()? What i’m i doing wrong?

I thought this would be simple to fix but to my surprise hours of online search got me turning in circles. Thanks in advance for your time!

class MyObject():

    def __new__(cls, myArg):
        
        stack = inspect.stack()[1]
        # If called by the create method of the MyObject class
        if stack[0].f_locals['cls'] == cls and stack[3] == "create":
            # Create object
            return super().__new__(cls, myArg=myArg)
        else:
            # Raise exception
            raise Exception("To create a new MyObject, use MyObject.create().")
    
    def __init__(self, myArg):
        
        self.myArg = myArg

    @classmethod
    def create(cls, myArg="test"):
        return cls(myArg=myArg)

I have seen multiple questions with answers about overriding __new__() but none of them take arguments.

LEAVE A COMMENT