Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Python doesn't remove the variables once a scope is closed (if there's such a thing as scope in Python, I'm not sure). I mean, once I finish a for variable in range(1, 100), the variable is still there, with a value (99 in this case).

Now I usually indent a whole block when I use the with ... as statement. But should I close the file and end the indentation as soon as I'm done with it? I mean, should I write:

with open('somefile', 'r') as f:
    newvar = f.read()

newvar.replace('a', 'b') # and etc

Instead of:

with open('somefile', 'r') as f:
    newvar = f.read()    
    newvar.replace('a', 'b') # and etc
share|improve this question
    
Do you have a more real concrete example? That's a trivial (and unrealistic) example. The motivations for choosing one approach over the other may be different depending on what is being done in the blocks. –  Jeff Mercado Feb 22 '13 at 15:25

1 Answer 1

up vote 3 down vote accepted

Yes, ideally, you close the with block as soon as possible, that way the file gets closed quickly - which means you are not (potentially) blocking access to it, having less file handles in use, etc...

Python does have scoping, it just doesn't make new scopes very often - only for functions and classes (and some other smaller cases, like list comprehensions and cousins in 3.x and above).

Unlike in Java, Python doesn't take the approach that every block is a scope, therefore loops, as you say in your question, don't introduce a new one.

share|improve this answer
    
thanks for making scopes clearer as well as answering the question :) –  barraponto Feb 22 '13 at 19:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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