Python Forum
How do I make an assignment inside lambda function?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I make an assignment inside lambda function?
#1
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?
Reply
#2
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
Reply
#3
micseydel, many thanks!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  not able to call the variable inside the if/elif function mareeswaran 3 610 Feb-09-2025, 04:27 PM
Last Post: mareeswaran
  Add two resultant fields from python lambda function klllmmm 4 1,978 Jun-06-2023, 05:11 PM
Last Post: rajeshgk
  with open context inside of a recursive function billykid999 1 1,342 May-23-2023, 02:37 AM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 1,937 May-02-2023, 08:40 AM
Last Post: Gribouillis
  Writing a lambda function that sorts dictionary GJG 1 2,665 Mar-09-2021, 06:44 PM
Last Post: buran
  How to make global list inside function CHANKC 6 4,303 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Parameters aren't seen inside function Sancho_Pansa 8 4,397 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  Practice problem using lambda inside the class jagasrik 3 3,096 Sep-12-2020, 03:18 PM
Last Post: deanhystad
  How to make this function general to create binary numbers? (many nested for loops) dospina 4 6,320 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  translating lambda in function fabs 1 2,695 Apr-28-2020, 05:18 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020