'Deleting python function reference

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.



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hrithik Pal