1

I am having difficulty to understand how del works in python. Should not del delete the object a after print it's value ?

def f1():
    a = 5
    def f2():
        print('a: ', a)
        del a
    f2()
    print(a)

f1()

By executing this function I am getting error:

UnboundLocalError: local variable 'a' referenced before assignment.

But if I don't delete a then it's working properly.

def f1():
    a = 5
    def f2():
        print('a: ', a)
        # del a
    f2()
    print(a)

f1()

Question:

  1. is del working at the same time as printing?
  2. if yes then it should be okay to understand but if not then is there anything I am missing?
Md Kamruzzaman Sarker
  • 2,387
  • 3
  • 22
  • 38
  • 1
    It seems like adding the `del a` statement makes the variable `a` a local. If you add `global a` before the `print('a: ', a)` it works as expected and deletes the global variable. – Bill Jul 22 '18 at 00:17
  • [Here](https://stackoverflow.com/questions/47717277/how-to-delete-a-global-variable-from-inside-a-function) is a similar question. – Bill Jul 22 '18 at 00:18
  • thanks. it may be the reason, but does del really make a non-global variable a local one? – Md Kamruzzaman Sarker Jul 22 '18 at 00:25
  • I am not sure to be honest. That was just my initial thought. Can anyone else explain? Maybe it's a safety feature to stop you accidentally deleting a global variable. – Bill Jul 22 '18 at 00:26
  • 2
    Same reason as https://stackoverflow.com/questions/49538724/why-is-ord-seen-as-an-unassigned-variable-here – user3483203 Jul 22 '18 at 00:27
  • That explains it. Thanks @user3483203! I guess `del a` is considered an assignment statement just like `a = 1`. – Bill Jul 22 '18 at 00:30
  • 1
    @Bill [Indeed](https://docs.python.org/3/reference/executionmodel.html#binding-of-names): "A target occurring in a `del` statement is also considered bound for this purpose (though the actual semantics are to unbind the name)." – Ondrej K. Jul 22 '18 at 11:12

0 Answers0