Can you assign variables in a lambda?

后端 未结 7 559
礼貌的吻别
礼貌的吻别 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.

提交回复
热议问题