user9212072
user9212072

Reputation: 13

Cannot delete python object instance

For an example, I have a class A:

def start(): 
    global object
    object = A()

def stop():
    del object

I got an error local variable 'object' referenced before assignment

I want to store a reference of the newly created object using the start function and delete the object reference using the stop function.

Is there any way to instantiate an object and delete an object instance using functions?

Thank you very much!

Upvotes: 0

Views: 601

Answers (2)

user9212072
user9212072

Reputation: 13

object = None

def start(): 
    global obj
    obj = {"dog": True}

def stop():
    global obj
    obj = None

thanks guys! I initiated the object with None, use global for both functions and set the variable to None instead for stop function

Upvotes: 1

LaytonGB
LaytonGB

Reputation: 1404

Using the name object is extremely bad practice because its a python keyword. Don't do that.

To delete globals inside a function you need to redeclare them first. See below.

def start(): 
    global obj
    obj = {"dog": True}

def stop():
    global obj # Re-declare.
    del obj
   
start()
print(obj) # {'dog': True}
stop()
print(obj) # NameError: name 'obj' is not defined

Note also that the mutation of globals, or deleting them in this case, is usually considered bad practice.

Upvotes: 0

Related Questions