Can you assign variables in a lambda?

后端 未结 7 508
礼貌的吻别
礼貌的吻别 2020-12-19 03:43

I was using a lambda statement to perform math, and happened to repeatedly use one certain value. Therefore I was wondering if it was possible to assign and use

相关标签:
7条回答
  • 2020-12-19 04:11

    Im no expert at this, but the way i did it was by modifying globals() or locals() like this:

    lambda: globals().__setitem__('some_variable', 'some value')
    

    or if it's inside a function:

    lambda: locals().__setitem__('some_variable', 'some value')
    

    you could also use update() instead of __setitem__() if you wanted to, but that's a bit redundant.

    0 讨论(0)
  • 2020-12-19 04:14

    You can create 2 different lambda functions and pass one to the other. For example,

    b = lambda x: 3+2*x
    a = lambda y: [my math here using variable b(y)]
    
    0 讨论(0)
  • 2020-12-19 04:18

    I've cooked up this recipe for python 3.8+ using PEP572 Assignment Expressions to assign arbitrary variables and execute arbitrary expressions.

    # python 3.8b1
    lambda a: (
        (bool(b:=a**2) or 1)
        and (bool(c:=a-b) or 1)
        and not print(f'compute: {a} + {b} + {c}')
        and (
            (ret:=a + b + c) or ret)
        )
    )
    tst(0) 
    # prints: "compute: 0 + 0 + 0"; returns: 0
    tst(1)
    # prints: "compute: 1 + 1 + 0"; returns: 2
    tst(8)
    # prints: "compute: 8 + 64 + -56"; returns: 16
    

    So the pattern is:

    lambda: [*vars]: (
        (bool(a:=[expr(*vars)]) or 1)
        and (bool([expr]) or 1)
        and bool([always true expr])
        and not bool([always false expr])
        and (
            # parentheses required so `result:=` doesn't capture the `or result` part
            (result:=[result expr]) or result
        )
    )
    

    This may be simplified if you know the truthiness of any particular expression.

    That being said, if you want to assign a variable to reuse inside a lambda, you probably should consider writing a normal function.

    0 讨论(0)
  • 2020-12-19 04:19

    You can instead use a bit of creativity, for example if you want to do some evaluation to an equation and assign the result to a variable it can be done like this:

    class Results:
        res = 0
    
    clas= Results()
    setattr(clas, 'res', 3+2*4)
    print(clas.res)
    
    0 讨论(0)
  • 2020-12-19 04:21

    You can assign variables in lambda functions is you use exec:

    >>> a = lambda: exec('global x; x = 1')
    >>>a()
    >>>x
    1
    
    0 讨论(0)
  • 2020-12-19 04:28

    You can just pass your lambda an argument which passes it along to another argument if you wish:

    >>> b = lambda x: 3 + 2*x
    >>> a = lambda y: y * b(y)
    >>> a(1)
    5
    >>> a(2)
    14
    
    0 讨论(0)
提交回复
热议问题