0

I have a simple module like this:

CMD_MAP = {
    "action": handler
}

def handler(x):
    print(x)

if __name__ == "__main__":
    CMD_MAP["action"]("hello")

When trying to run/import it, it throws a

  File ".../example.py", line 2, in <module>
    "action": handler
NameError: name 'handler' is not defined

However, when I change the CMD_MAP to :

CMD_MAP = {
    "action": lambda x: handler(x)
}

it works without issues. Can someone explain why?

1
  • Everytime you put parens in front of a name you are calling that name. Even if you defined handler before CMD_MAP, it will not work as expected because the "action" key would hold None (the handler function has no return) Commented May 11, 2020 at 17:13

1 Answer 1

4

The body of the lambda isn't evaluated until the lambda is called. In your first example, you try to call handler before it's been defined, so you get an error. In your second example, handler gets called after it's been defined, so it's fine.

Sign up to request clarification or add additional context in comments.

2 Comments

worth mentioning that the first example is a mistake anyway, it should be "action": handler not "action": handler(x) to be equivalent to the lambda.
@Dan, yep - shody copying on my part, thanks for pointing it out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.