[Tutor] how to make an lexical scope block?

Steven D'Aprano steve at pearwood.info
Sat Aug 5 05:38:56 EDT 2017


On Sat, Aug 05, 2017 at 03:23:57PM +0800, Xiaosong Chen wrote:
> In C, it's a common pattern to use temporary variables in an lexical
> scope to prevent the global scope from getting dirty.
[...]
> But in python, such a pattern seems impossible. An straightforward
> translation should be like this:
> 
> ```python
> a = []
> for i in range(N):
>     temp = ...
>     a.append(...)# something got from temp
> # temp DO EXISTS here, will be the value of the last iteration
> ```
> 
> As in the comment, the temporary variable remains existing after the
> block. How do you usually deal with this?


If you use functions (or methods), as you should, then temp will be a 
local variable of the function, and it doesn't matter if it still exists 
after the for loop. It is hidden inside the function scope, and cannot 
affect the global scope.

If you are using global scope, as sometimes is needed, then it depends. 
If this is a script that you run, then it really doesn't matter. A few 
temporary variables more or less doesn't make the script any better or 
worse. Don't worry about it.

If it is a library, where a nice clean global namespace is important, 
you can either refactor the code to make the problem go away, or delete 
the name when you are done:

del temp

deletes the name "temp" from the current namespace.

-- 
Steve


More information about the Tutor mailing list