0

I have a place in my script where I am asking user for some feedback (selecting the next stage in the script) and due to huge amount of items user is making decision from I wrapped my 'if-else' part into a dictionary. I am able to call any 'plain' function, but in a lot of cases I have to call the same function but with some arguments, but cannot figure out how to add these to the body of the script I already have. It looks like this (I will try to comment it so you see where I have a problem):

def runthis():

    # getting user input
    decide = input(str(
        'Select option 1'
        'Select option 2'
        'Select option 3'
        'Select option etc'
        'Select option n'))

    # each action listed here as a function without parentesis and arguments
    options = {
        '1': func1,
        '2': func2,
        '3': func3,
        'etc': funcetc,
        'n': funcn}

    # go through the list and look for key matching user decision
    # then run the value as a function - how to pass arguments when I need?
    if decide in options.keys():
        options[decide]()
    else:
        print('invalid entry')
        runthis()


runthis()

Thanks, any help much appreciated.

1

2 Answers 2

1

Answer is simple - for the ones I need to add arguments I will just call the value as lambda ... like this:

# say func 2 holds 3 arguments
options = {
    '1': func1,
    '2': lambda: func2(arg1, arg2, arg3),
    '3': func3,
    'etc': funcetc,
    'n': funcn}

So easy solution and one does not see it

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

Comments

1

The functools module provides you means of manipulating functions including partial which allows you to partially pass in the arguments to a function, e.g.:

import functools
options = {
    ...
    '2': functools.partial(fn, arg1, arg2, arg3)
    ...
}

1 Comment

didn't know that, thanks. I am still learning and functools is not even on my list 'need to know now' :-) actually isn't than the lambda solution better? (no import, easier syntax)

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.