0

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!

8
  • 1
    del doesn't delete objects to begin with Commented May 14, 2021 at 16:31
  • 1
    Don't call your variable object (or list or dict or...) - having said which, your stop routine hasn't been told that there is a global it should be looking at. Commented May 14, 2021 at 16:32
  • 1
    Anyway, you have to use global in stop. But be aware, using global mutable state like this is usually considered bad design Commented May 14, 2021 at 16:33
  • 1
    del is rarely needed. It doesn't delete an object; it removes a name from a scope (or invokes __delitem__ or __delattr__ in the case of del x[i] or del x.i). An object may be deleted, if you removed the last reference to the object. Commented May 14, 2021 at 16:40
  • 1
    beside advices from other comments: avoid using global variables if possible, you'll have bad time when your codebase will get bigger. Commented May 14, 2021 at 16:44

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.