"Chris Rebert" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
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

Also, you don't need a lambda for this example:

class Blah(list): pass
...
d={1:Blah}
d[1]()
[]

-Mark

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to