How to define a temporary variable in python?

Does python have a “temporary” or “very local” variable? I am looking for one liner and I want my variable space to be neat.

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 ix variable will be undefined outside of one line.

Perhaps this pseudo code is clearer:

...a and b are populated lists earlier in code...
{ix=getindex(); answer = f(a[ix]) + g(b[ix])}

where ix does not exist outside the parenthesis.

+4
source share
3 answers

Generator concepts and expressions have their own scope, so you can put them in one of the following:

>>> 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 need to worry about that. This is 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

Python 3, print .

+3

, : , ( , ), , , python dict list.

, lambda,

0

python "" " " ?

, , . :

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 scope
> NameError: name 'bar' is not defined

, , , . , del:

bar = 'foo'
print bar # works
> foo
del bar
print bar # fails
> NameError: name 'bar' is not defined

Note that this does not directly release the string object 'foo'. This is the work of the Python garbage collector, which will clean up after you. However, in almost all cases there is no need to deal with untying or gc explicitly. Just use variables and enjoy Python livestyle.

0
source

Source: https://habr.com/ru/post/1653984/


All Articles