0

I have been using python for more than a year now but I am confused by something in this example:

def mul(x,y): return x*y

def setArg(f,a):
    def fx(*x):
        return f(*x,a)
    return fx

def test1():
    mul3=setArg(mul,3)

def test2():
    mul=4

def test3():
    mul=setArg(mul,3)

def test4():
    mu=setArg(mul,3)
    mul=mu

running test1 and test2 works fine,but running test3 and test4 give this error: UnboundLocalError: local variable 'mul' referenced before assignment

Can I only redefine mul inside a testX globally? Why is so in python? using python3.7

vaibhav chaturvedy
  • 126
  • 1
  • 1
  • 6
  • not entirely as I am more confused now due to 'nonlocal' in the answer – vaibhav chaturvedy Nov 21 '19 at 18:36
  • Ok, but the first paragraph of the answer explains the problem. Let me summarize it again: `mul = ` means that `mul` refers to a local variable and the assignment will give it a value. A variable (local or not) has no value before the first assignment. That's why `... = setArg(mul, 3)` expression fails to evaluate. Maybe this helps a little bit too: https://en.wikipedia.org/wiki/Variable_shadowing#Python – VPfB Nov 21 '19 at 18:47

1 Answers1

4

It's the argument 'mul' that is the problem, not the assignment to 'mul'. You can use both global and local with mul=setArg(globals()['mul'],3).

Wim Lavrijsen
  • 3,453
  • 1
  • 9
  • 21