Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a temporary variable in python?

Tags:

python

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.

like image 201
Michael Ehrlichman Avatar asked Sep 08 '16 09:09

Michael Ehrlichman


2 Answers

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.

like image 197
TigerhawkT3 Avatar answered Oct 21 '22 07:10

TigerhawkT3


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.

like image 45
miraculixx Avatar answered Oct 21 '22 06:10

miraculixx