Search code examples
pythonvariablesparametersinquirer

Storing function parameters within a variable


I'm trying to store parameters in a variable to later be used in a function, such as simple InquirerPy question.

A simple, functional question might look like this:

from InquirerPy.separator import Separator
from InquirerPy import inquirer

inquirer.select(
        message = "Select an action:",
        choices=[
            "Upload",
            "Download",
            Separator(),
            "Other"
        ]
).execute()

However, as large parts of questions are identical, I would like to store the question and parameters and them use them later. Something like this:

question_details = (
    message = "Select an action:",
    choices=[
        "Upload",
        "Download",
        Separator(),
        "Other"
    ],
    )   
inquirer.select(question_details).execute() # Fails
# SyntaxError: invalid syntax

But this gives me a syntax error. I thought I could maybe store the parameters as a string to stop them being evaluated:

question_details = {' \
    message="Select an action:", \
    choices=[ \
        "Upload", \
        "Download", \
        Separator(), \
        "Other" \
    ], \
    '}
inquirer.select(question_details).execute() # Fails
# TypeError: __init__() missing 1 required positional argument: 'choices'

However it doesn't recognise the string as a set of parameters and fails.

How can I store these parameters so they aren't evaluated before being stored, but can still be read correctly later when they are used by my InquirerPy function?

The documentation is here but I don't think anyone will need it.


Solution

    • Store keyword parameters as a dictionary: question_details = {"message": "Select an action:", "choices": [...]).
    • Use double-asterisk to use dictionary for keyword parameters in the actual call: inquirer.select(**question_details).execute().