Python Forum

Full Version: How do I make an assignment inside lambda function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good day,
having a brain freeze :) How do I set a boolean variable to True inside lambda function? I'm trying to set variable to True on a hotkey(using SystemHotkey lib) :

from system_hotkey import SystemHotkey

b = False
SystemHotkey().register(('control', 'e'), callback = lambda : b = True)
But this spits out a syntax error.  Also tried:
SystemHotkey().register(('control', 'e'), callback = lambda : exec('b = True'))
But it just doesn't work. Any ideas, please?
Lambas in Python must be an expression. Assignments are statements. Things like return, break, continue, the equals sign, and that are all statements. While and for loops are also not expressions, although comprehensions are expressions. exec is also a statement, not a function (since functions can be used for expressions) and eval(), though a function, has the same limitation as lambdas that it cannot handle statements.

Basically, you cannot do it this way. You would probably be better off encapsulating the state in a class, and creating a method that mutates that variable internally anyway, e.g.

class State:
   def __init__(self):
       self.b = False

   def setB(self, setTo):
       self.b = setTo

state = State()

SystemHotkey().register(('control', 'e'), callback = lambda: state.setB(True))

# use state.b elsewhere
micseydel, many thanks!