0

I find this one entirely confounding. The below code runs fine:

def vendor(title, description):
    def validate():
        print("in validate, title: ", title)
        print("in validate, description: ", description)
        convert()
    def convert():
        print("\nin convert, title: ", title)
        print("in convert, description: ", description)
        if title == "fedex":
            pass
            #description = "something else"
    validate()
vendor("ups", "stuff")    

But substitute pass with a reassignment like description = "something else" and I get UnboundLocalError: local variable 'description' referenced before assignment. If I take out print("in convert, description: ", description) the program runs without error.

What gives? How am I referencing description before assignment? Also, it doesn't seem to matter if a pass vendor() "fedex" or something else like "ups" as the title, I still get the error message. How would I go about doing what I'm trying to do - reassign a variable (albeit a function parameter) if a certain condition is True?

Thanks in advance!

Big Sharpie
  • 829
  • 2
  • 9
  • 23
  • 3
    there are alot of this almost exact answer already on SO ... try looking in the related links on the side of your question – Joran Beasley Jul 02 '14 at 18:12
  • 1
    IIRC if you perform an assignment to a name inside a function it's treated as a function local across the function. You can't assign to the variable you're closing over unless you pass the instance holding it as a member – Daenyth Jul 02 '14 at 18:15
  • Hint - [`nonlocal`](https://docs.python.org/3/reference/simple_stmts.html#nonlocal) – Sean Vieira Jul 02 '14 at 18:27
  • Why on earth is your code structured like that? – jonrsharpe Jul 02 '14 at 18:27
  • @jonrsharpe I'm not sure what you mean. How could I structure it better? – Big Sharpie Jul 02 '14 at 18:36
  • Well you could have functions that take arguments rather than relying on scoping, return values or even actually do something. – jonrsharpe Jul 02 '14 at 18:44

0 Answers0