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
  Add two resultant fields from python lambda function klllmmm 4 904 Jun-06-2023, 05:11 PM
Last Post: rajeshgk
  with open context inside of a recursive function billykid999 1 570 May-23-2023, 02:37 AM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 787 May-02-2023, 08:40 AM
Last Post: Gribouillis
  Writing a lambda function that sorts dictionary GJG 1 2,011 Mar-09-2021, 06:44 PM
Last Post: buran
  How to make global list inside function CHANKC 6 3,075 Nov-26-2020, 08:05 AM
Last Post: CHANKC
  Parameters aren't seen inside function Sancho_Pansa 8 2,881 Oct-27-2020, 07:52 AM
Last Post: Sancho_Pansa
  Practice problem using lambda inside the class jagasrik 3 2,154 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 4,395 Jun-24-2020, 04:05 AM
Last Post: deanhystad
  translating lambda in function fabs 1 2,147 Apr-28-2020, 05:18 AM
Last Post: deanhystad
  Lambda function recursion error DeadlySocks 1 2,046 Apr-13-2020, 05:09 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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