0

I would like to know if it is possible to inset an extra scope within my code, without defining a function. The problem that I had was as follows:

def func(a, b, c):
   some_var = [a for a in b]
   # do stuff with a

My expectation was that a is still the value that I passed to the function, since I expected the other a to be in the scope of the list comprehension (had to search for that bug for ever!).

How can I rewrite it so that the a in the list comprehension is in its own scope?

I would like to have something more elegant than

def func(a, b, c):
   def helper(v): 
       return [a for a in v] 
   some_var = helper(b)
   # do stuff with a

In languages where the scope is defined by using {}, you could do stuff like

def func(a, b, c) {
   some_var = null
   {
       some_var = [a for a in b]
   }
   # do stuff with a
}

Is there something similart in Python?

Ralf
  • 16,086
  • 4
  • 44
  • 68
User12547645
  • 6,955
  • 3
  • 38
  • 69

3 Answers3

2

If you can, move to python 3. List comprehensions in python 2 are known to leak variables into the namespace.

If not however, you can mimic a clean list comprehension by using generator expressions which do not leak variables, wrapped in a list call.

def func(a, b, c):
   some_var = list(a for a in b) #Does not leak a
   # do stuff with a
Paritosh Singh
  • 6,034
  • 2
  • 14
  • 33
2

You can insert an extra scope by wrapping the list comprehension by a dict comprehension for example:

>>> {None: [x for x in range(5)] for __ in range(1)}.values()[0]

This won't leak the value of x but it's not really readable.

a_guest
  • 34,165
  • 12
  • 64
  • 118
0

If you are just creating a copy of b, isn't it easier to just do:

def func(a, b, c):
   some_var = b[:]

No need to worry about a being in an extra scope and what not.

r.ook
  • 13,466
  • 2
  • 22
  • 39