0

I want to create some kind of user interface and the user should be able to type the name of the function he wishes to run:

task = input('Programm to run: ')

Once task is defined I want to execute the desired task like:

task()

If for example the desired program is functonthe script shall execute function().

3
  • 3
    If you're fine to stick to functions for now, your question was already answered on SO Invoking top-level function by name in Python Commented Oct 28, 2016 at 22:20
  • 1
    The duplicate question is strictly for invoking top level functions which is not a great idea, and OP need not do that for their use case. The accepted answer allows 'calling' any variable in the top level scope which may be a bad idea. The other options have annoying boilerplate which mentions each function name thrice. Commented Oct 28, 2016 at 22:27
  • 1
    @AlexHall - I don't think there's any problem with it. Personally, I would've used the popular variable variables question, but the linked duplicate is a bit more specific. A dictionary is the popular way to do this. Commented Oct 28, 2016 at 22:29

3 Answers 3

1

Here is another way for doing it globally:

def foo():
    print("foo")


def bar():
    print("bar")


method = input("What method: ")  # ask for method
globals().get(method, lambda: 0)()  # search for global method and execute it
Sign up to request clarification or add additional context in comments.

Comments

1

Like said in the comments, you can create a dictionary and run the functions from it:

def func1(): print('I am f1')
def func2(): print('I am f2')
def func3(): print('I am f3')


functions = {'f1': func1, 'f2': func2, 'f3': func3}

x = input('which function:')
functions[x]()  # call the function

Comments

0

Here's one way:

class Tasks(object):
    def foo(self):
        print('hi')

    def bar(self):
        print('bye')


task = 'foo'

getattr(Tasks(), task)()

5 Comments

A dictionary would probably be a more natural container for string-keyed functions than an instance in this situation.
Yes but that requires more boilerplate and name duplication. One might define a function and then forget to add it to the dictionary.
Hmm, fair enough. Since your class is being used solely as a namespace for its methods and not to hold any data, perhaps you should make the methods static and look them up directly on the class, rather than on an instance?
I think it's a matter of opinion as to whether a string key for each function is more boilerplate than a class plus getattr.
@TigerhawkT3 it's constant boilerplate which you copy paste once. If there are 10 functions and you keep adding more the dictionary clearly loses.

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.