1

I would like to know if there is a Python equivalent to this JavaScript construct:

var myFunctions = {
    'greet': function(name){
        return "Hello, " + name;
    },

    'farewell': function(time){
        return "See you " + time;
    }
}

So I can call the functions this way:

let greetMarta = myFunctions['greet']("Marta");
2
  • All functions are first-class objects in Python. Are you asking about anonymous functions? Commented Jan 23, 2018 at 9:43
  • 1
    Yes you can put functions in a dictionary in Python. Commented Jan 23, 2018 at 9:44

3 Answers 3

5

You can use lambda to define very simple functions like these inline; however they can only consist of one expression:

    my_functions = {
        'greet': lambda name: "Hello {}".format(name),
        'farewell': lambda time: "See you {}".format(time)
    }

For anything more complicated you need to define a standalone function and then reference it in the dict:

    def my_complex_function(param):
        ... logic ...
        return whatever

    my_functions = {
        'complex_func': my_complex_function,
        ...
    }

And in order to call the function you can do:

my_functions['my_complex_function'](param)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Show me how I would call it pls
Exactly the same as in JS: my_functions['greet']('Victor').
1
def greet(name):
    return "Hello, " + name

def farewell(time):
    return "See you " + time

my_functions = 
{
    "greet": greet,
    "farewell": farewell
}

Comments

1
def greet(name):
    return "Hello, " + name;

def farewell(time):
    return "See you " + time;

my_dict = {'greet' : greet, 
           'farewell' : farewell}

greetMarta = my_dict['greet']("Marta");

use dictionary to get the functions and execute

Comments

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.