0

I have function defined like this:

def foo(karg=None):
    def bar():
        print(karg)
        if karg is None:
            karg = None

    return bar

foo()()

Running above code results in following error:

Traceback (most recent call last):
  File "/home/xps/a.py", line 10, in <module>
    foo()()
  File "/home/xps/a.py", line 3, in bar
    print(karg)
UnboundLocalError: local variable 'karg' referenced before assignment

If I delete if branch in above function, code runs just fine:

def foo(karg=None):
    def bar():
        print(karg)

    return bar

foo()()

Shouldn't karg be visible all throughout bar() function?

  • Does [this](https://stackoverflow.com/a/9264845/16757174) answer your question? This question is also answered on the [Python official FAQ](https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value) – kcsquared Sep 09 '21 at 15:27
  • It does. Thank you. – user1233334232221 Sep 09 '21 at 15:34

0 Answers0