I saw this snippet in a code that I am working on. And I feel that accessing the outer function variable directly in the inner function brings some undesirable magic. For e.g. when I read the function, I assume that the variables I am manipulating in that function is gotten from the parameters

def outer_function():
    filename = os.path.abspath("some.config")

    def inner_function(state):
        with open(filename, "w+") as f:
        os.rename(filename + ".ext" , filename)
  • What are the drawbacks of inner_function accessing the variable filename directly from it's immediate outer scope?
  • Are there any stylistic drawbacks/concerns in this snippet of code?

You'll be fine in this case, since the interpreter will look in the enclosing scope of inner_function after failing to find filename in the local scope. However, there are some ways in which scope resolution can trip you up. For example, if you try and change filename within inner_function you'll run into problems like in this Stack Overflow post.

It's not clear what you're doing with os.rename(filename + ".ext" , filename). Your code doesn't create a .ext file, and if it renaming it would overwrite the file at filename anyways.


Not the answer you're looking for? Browse other questions tagged or ask your own question.