Home > other >  Deleting python function reference
Deleting python function reference

Time:01-29

When I wrote the following code, it executes fine:

def hello():
    print("Hello")


def test():
    r = hello
    r()


if __name__ == '__main__':
    test()

Then, I tried deleting the hello function reference:

def hello():
    print("Hello")


def test():
    r = hello
    r()
    del hello


if __name__ == '__main__':
    test()

But I received the following error:

Traceback (most recent call last): File "/Users/deepak.ahire/Documents/my_projects/testing_decorators/main.py", line 12, in

test()

File "/Users/deepak.ahire/Documents/my_projects/testing_decorators/main.py", line 6, in test

r = hello

UnboundLocalError: local variable 'hello' referenced before assignment

What is the cause for this? As I wrote the del statement after r = hello.

CodePudding user response:

@Iain Shelvington have already answered your question, but just adding to that, If you disassemble your code del emits DELETE_FAST Opcode and by looking at it's the source code, you can see that it will try to lookup hello(oparg in this case is hello) from local variables of function test, if it not found, this will result in unbound_local_error(UnboundLocalError exception in python layer)

TARGET(DELETE_FAST) {
    PyObject *v = GETLOCAL(oparg);
    if (v != NULL) {
        SETLOCAL(oparg, NULL);
        DISPATCH();
    }
    goto unbound_local_error;
}

CodePudding user response:

It is caused because you want to delete "hello" before it is assigned and here " hello " acts like a variable so, instead of doing that you can write your code like :

def hello():
print("Hello")
def test():
    r = hello
    r()
    del r
if __name__ == '__main__':
     test()

here , you can't delete the function call but can delete the class function

  •  Tags:  
  • Related