Note: Actual code was not as straightforward, func2 was actually a decorator. Admittedly, using the same parameter name is not a must, but it’s still a curiosity. I just wanted to fall back to a default value on run-time.

If you’re curious, you can read about the principles of LEGB. You have to understand a bit about compilers and the AST to get what’s going on behind the scenes. You might think that replacing lines 3-4 with:

param = param or 'default'

Might work. But no. You can’t assign the same parameter at the local level if the enclosing level defines it. Even this fails:

param = param

Fun, no?

What to do?

There are a few ways to get around this.

Assign param outside of func2. This doesn’t work if you need the default value to be dependent on what params func2 receives.

Read more

2 responses

You don’t reach a conclusion here I think I do understand why this is happening, but you might want to add a sentence or two next time resolving the issue in plain English — that’ll help people who come here when googling for this problem.

I'm a full time web developer for Mozilla, with main focus on Django, Python, and JavaScript. I have a B.S.C.S. from UCSC. I’ve been involved with Mozilla since 2008. If you're interested in more about me and what I do, check out my blog or follow me on twitter.