11

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.

6
  • 1
    You can del ix when you don't need it anymore. Commented Sep 8, 2016 at 9:08
  • why not just {answer = f(a[getindex()]) + g(b[getindex()])}? Commented Sep 8, 2016 at 9:09
  • @Andrew getindex() might be inefficient. Commented Sep 8, 2016 at 9:09
  • 2
    You could do answer = (lambda ix=getindex(): f(a[ix]) + g(b[ix]))(). But please don't. Commented Sep 8, 2016 at 9:11
  • @galah92 ix=getindex(); ans=f(a[ix]) + g(b[ix]); del ix; does accomplish what I need. But if I would still like to know if there exists a variable localization facility. Commented Sep 8, 2016 at 9:20

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

That is only valid syntax in Python 3
next(range(5)[x] for x in [1]) will work in Python 2.7, and it doesn't leak x to the surrounding scope
@cdarke - OP seemed to be using Python 3, and didn't say anything about specifically wanting to put statements into such a construct. What statement other than Python 2's print (which can be masked with from __future__ import print_function) would be useful in this situation, anyway?
@cdarke - I've added a Python 2-friendly version for you. :)
I was only pointing it out for future reference, its wasn't meant as a criticism!
1

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.

Comments

0

Technically not an answer, but: Don't worry about temporary variables too much, they are only valid within their local scope (most likely function in your case) and garbage collector gets rid of them as soon as that function is finished. One liners in python are mostly used for dict and list comprehensions.

If you REALLY want to do it in one line, use lambda which is pretty much keyword for inline function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.