1

I wondered if there is a way to pass a dict to the arguments of a RequestParser .add_argument() command

it normally works like this

    my_parser = reqparse.RequestParser()
    my_parser.add_argument('my_field', type=dict, help='my_field must be a dict', required=True)

For code re-usability purposes, I'd like to use it somewhat like this

    my_arguments = {type=dict, help='my_field must be a dict', required=True}

and then pass these as arguments to the .add_argument function using:

    my_parser.add_argument('my_field', my_arguments)

I got stuck trying to do this using list comprehension,

    my_parser.add_arguments('my_field', list(key=value for (key, value) in parser_arguments.items()))

at which point I realized I probably can't use a dict, might need to do a getattr() and clearly investing too much time on this. It seems possible and elegant to me, but I can't find a solution anyway, thankful for any enlightening ideas on this.

Edit: I can't use the intuitive

    my_parser.add_argument('my_field', my_arguments)

because the dict will be added to the "default" field of the parser argument, and the actual fields ("type", "help" and "required") are unaffected.

1

1 Answer 1

1

You can use kwargs unpacking:

my_arguments = {'type':dict, 'help':'my_field must be a dict', 'required':True}
my_parser.add_argument('my_field', **my_dict)

Which is equivalent to

my_parser.add_argument('my_field', type=dict, help='my_field must be a dict', required=True)
Sign up to request clarification or add additional context in comments.

1 Comment

I swear I tried that, I must have had an error in the dict itself when I did. This obviously works perfectly.

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.