On Fri, Nov 7, 2008 at 8:52 PM, pineapple <[EMAIL PROTECTED]> wrote: > I am not a python programmer, but am being forced to port one of my > (smalltalk) applications to python for pragmatic reasons (python is > embedded with a graphics package I am switching over to, so to use the > graphics package I am essentially forced to use python). Okay, enough > background. > > At any rate, in my smalltalk solution, in order to avoid an if-then- > else chain of "if this command, do this function, else if this command > do another function..." I have commands set up in a dictionary. I > read the command integer, then key it into the dictionary to see what > method/function to call. > > #Conceptual representation of dictionary with keys and values: > > 1: do_command1 > 2: do_command2 > 3: etc... > > Trying to set up the same thing in python, it seems the lambda > expression is what I need. So I set up a simple class to test this, > with some simple code as follows: > > ### > class Blah(list): > pass > > commands = {1: (lambda: Blah())} > ### > > This is accepted by the interpreter, no problem. If I type "commands" > into the interpreter I get the dictionary back showing the key '1' > attached to the lambda expression. If I type "commands[1]" into the > interpreter, I get the lambda function back. However, when I try to > invoke the lambda function with a "commands[1]()", I get a "global > name 'Blah' is not defined." I find this error odd, because if I do a > "Blah()", I get back a "[]" as expected (a list).
The code you gave works perfectly: chris ~ $ python Python 2.5.1 (r251:54863, Feb 4 2008, 21:48:13) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> class Blah(list): ... pass ... >>> commands = {1: (lambda: Blah())} >>> commands[1]() [] Please post some of the actual code so that we can determine the problem. Taking a guess, I'd suspect Blah and commands are in different modules and you didn't import Blah into commands' module, hence why Python can't find it. But we'd need some more details to be able to determine that. Cheers, Chris -- Follow the path of the Iguana... http://rebertia.com > > For a day, I have tried everything under the sun I know to try. For > instance, I thought perhaps lambdas don't work with methods, so I > wrapped the method call in a function. But I get the same error. I > have spent a day online googling this error, but have found nothing to > help me. > > Can a guru out there help a python newbie with this? I figure you can > spot the problem in, oh, 5 seconds or less? > > Thanks > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list