Super Tip: Pass Arguments in your Python Bindings using Lambda Functions

| No Comments »

Problem: Help! How can I pass parameters in my Bindings?

Solution: By using lambda functions in python(Check your PL’s manual for anything similar), you would be able to create on-the-fly functions that returns your bindings with the extra parameters/arguments you want to pass.

Example 1: Passing an argument to a wx Button Event

btn = wx.Button(self, 10, “Button”, (10, 10)) self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, ‘passthis’)) def OnClick(self, event, somearg):    print somearg

Example 2: Passing an argument to Pyhook’s HookManager.KeyUp Event

hook = pyHook.HookManager() hook.KeyUp = lambda event: OnKeyboardEvent(event, ‘Pass Me.’) hm.HookKeyboard() def OnKeyboardEvent(event, myarg)   print myarg

That’s It!

How to: Count your regex pattern matches in python

| No Comments »

Problem: I need to display the number of times my regex has matched.

Solution: No Problem! Use the len (abbrev. for length) function:

import re >>> regex = re.compile(r”your pattern here…*”) >>> match = regex.findall(“the contents…”) >>> len(match) 10

That’s It!

On a side note, you can also use len to count the number of characters in a string.

>>> text = “All your base…” >>> len(text) 16