0

I have a list of intended function names e.g. ['check_one', 'check_two', 'check_three'] and would like to create Python functions using them as function names.

The following doesn't work:

for func_name in ['check_one', 'check_two', 'check_three']:
    def f'{func_name}'(text):
        print(text)

The intended effect is that I have three functions defined as follows:

check_one('one fine day') # This function checks for the presence of the exact word 
                          # 'one' in the argument. It should return integer 1 if True, 
                          # and 0 if False. An example of a False result would be 'oneone fine day'.
check_two('hello world')  # Likewise, this function checks for the presence of the word 
                          # 'two' in the argument. In this case, it should return a 0.
check_three('c')          # Likewise

My original function is:

def check_one(string):
    return int((' ' + 'one' + ' ') in (' ' + string + ' '))

So I'd like a way to generate these functions through a loop, by providing a list of function names ['check_one', 'check_two', 'check_three'].

Would appreciate any help. Thank you!

2

2 Answers 2

3

If you have something more complex than a lambda can represent, you'd probably want to make a function that creates/returns new functions, and then use a process similar to what @Samwise's answer describes:

def create_function():
    def f(text):
        print(text)
    return f

functions = {
    func_name: create_function()
    for func_name in ['check_one', 'check_two', 'check_three']
}

functions['check_one']("Hello World!")

# to get them out of a dict and into the local namespace, 
# update the local namespace directly
locals().update(functions)
check_one("Hello World!")

Depending on what you need to attach the functions to (e.g. a class or module) you can use the appropriate methods to insert the functions into that object's personal namespace instead of the runtime local namespace, replacing locals().update() accordingly.

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

Comments

0

Put them in a dict:

>>> functions = {
...     func_name: lambda text: print(text)
...     for func_name in ['check_one', 'check_two', 'check_three']
... }
>>>
>>> functions["check_one"]("Hello World!")
Hello World!

3 Comments

I don't think this is answering the OP question as he wants to be able to call them as usual functions.
There's nothing "unusual" about these functions.
I was referring to the fact that the OP wants to call the functions like this: check_one() not like this: functions["check_one"]()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.