Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.
I would like to do something like this:
...a, b, and c populated as lists earlier in code...
using ix=getindex(): print(a[ix],b[ix],c[ix])
...now ix is no longer defined...
The variable ix would be undefined outside of the one line.
Perhaps this pseudo-code is more clear:
...a and b are populated lists earlier in code...
{ix=getindex(); answer = f(a[ix]) + g(b[ix])}
where ix does not exist outside of the bracket.
Comprehensions and generator expressions have their own scope, so you can put it in one of those:
>>> def getindex():
... return 1
...
>>> a,b,c = range(2), range(3,5), 'abc'
>>> next(print(a[x], b[x], c[x]) for x in [getindex()])
1 4 b
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
But you really don't have to worry about that sort of thing. That's one of Python's selling points.
For those using Python 2:
>>> print next(' '.join(map(str, [a[x], b[x], c[x]])) for x in [getindex()])
1 4 b
Consider using Python 3, so you don't have to deal with print
as a statement.
Does python have a "temporary" or "very local" variable facility?
yes, it's called a block, e.g. a function:
def foo(*args):
bar = 'some value' # only visible within foo
print bar # works
foo()
> some value
print bar # does not work, bar is not in the module's scope
> NameError: name 'bar' is not defined
Note that any value is temporary in the sense that it is only guaranteed to stay allocated as long as a name is bound to it. You can unbind by calling del
:
bar = 'foo'
print bar # works
> foo
del bar
print bar # fails
> NameError: name 'bar' is not defined
Note that this does not directly deallocate the string object that is 'foo'
. That's the job of Python's garbage collector which will clean up after you. In almost all circumstances there is however no need to deal with unbinding or the gc explicitely. Just use variables and enjoy the Python livestyle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With