Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variable to local scope of function in Python

Tags:

python

lambda

I'd like to assign a variable to the scope of a lambda that is called several times. Each time with a new instance of the variable. How do I do that?

f = lambda x: x + var.x - var.y

# Code needed here to prepare f with a new var

result = f(10)

In this case it's var I'd like to replace for each invocation without making it a second argument.

like image 704
Jonas K Avatar asked Sep 15 '26 06:09

Jonas K


2 Answers

Variables undefined in the scope of a lambda are resolved from the calling scope at the point where it's called.

A slightly simpler example...

>>> y = 1
>>> f = lambda x: x + y
>>> f(1)
2
>>> y = 2
>>> f(1)
3

...so you just need to set var in the calling scope before calling your lambda, although this is more commonly used in cases where y is 'constant'.

A disassembly of that function reveals...

>>> import dis
>>> dis.dis(f)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_GLOBAL              0 (y)
              6 BINARY_ADD
              7 RETURN_VALUE

If you want to bind y to an object at the point of defining the lambda (i.e. creating a closure), it's common to see this idiom...

>>> y = 1
>>> f = lambda x, y=y: x + y
>>> f(1)
2
>>> y = 2
>>> f(1)
2

...whereby changes to y after defining the lambda have no effect.

A disassembly of that function reveals...

>>> import dis
>>> dis.dis(f)
  1           0 LOAD_FAST                0 (x)
              3 LOAD_FAST                1 (y)
              6 BINARY_ADD
              7 RETURN_VALUE
like image 146
Aya Avatar answered Sep 17 '26 20:09

Aya


f = functools.partial(lambda var, x: x + var.x - var.y, var) will give you a function (f) of one parameter (x) with var fixed at the value it was at the point of definition.

like image 38
Chris Wilcox Avatar answered Sep 17 '26 21:09

Chris Wilcox