[Tutor] how to make an lexical scope block?

Peter Otten __peter__ at web.de
Sat Aug 5 05:28:14 EDT 2017


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.
> For example,
> 
> ```C
> int a[N];
> for (int i = 0; i < N; i++) {
>   int temp = ...
>   a[i] = ... // something got from temp
> }
> // temp do not exists here
> ```
> 
> 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?

I put the code into a function

def create_a(n):
    result = []
    for i in range(n):
        temp = ...
        result.append(...)
    return result

a = create_a(N)

At this point you could delete the function

del create_a

but in practice I never do that. 

If you want to go fancy you can rewrite the above as

def replace_with_result(*args, **kw):
    def call(f):
        return f(*args, **kw)
    return call

@replace_with_result(N)
def a(n):
    result = []
    for i in range(n):
        temp = ...
        result.append(...)
    return result

which will immediately overwrite the function a() with the result of the 
a(N) call -- but I prefer to keep the function around. 

The extra memory is usually negligible, and writing unit tests to detect 
blunders in create_a() is always a good idea, as trivial as it might appear 
on first sight...



More information about the Tutor mailing list