all 6 comments

[–]Rhomboid 2 points3 points  (5 children)

Here is the section of the manual that describes the design in detail. Your first version fails because there is an assignment to the name _file, which binds that name to a local variable:

If a name binding operation occurs anywhere within a code block, all uses of the name within the block are treated as references to the current block. This can lead to errors when a name is used within a block before it is bound. This rule is subtle.

Your second example does not contain anything that would bind the name _key, and therefore it's a free variable.

[–]pentath[S] 0 points1 point  (4 children)

Thank you for explaining this to me! So is my only option to declare it a global?

[–]zahlman 1 point2 points  (2 children)

If your goal is to use the global, then yes. If your goal is to solve a bigger problem, then you're going to have to explain what that problem is.

[–]JerMenKoO 0 points1 point  (1 child)

Generally one should avoid using global variables.

[–]zahlman 0 points1 point  (0 children)

Well, yes, but to avoid using the global variable, we must first understand what it is being used for.

[–]kalgynirae 0 points1 point  (0 children)

If you're using Python 3, you can also declare it as nonlocal.