Why does inputParser allow a required argument to also be input as a name-value pair?
6 views (last 30 days)
Show older comments
In R2013b, with a mix of addRequired and addParameter definitions, if the user happens to supply a name-value pair using the same name as the required argument, the value from the name-value pair takes precedence. Example code:
function [] = parsertest( req, varargin )
p = inputParser;
p.addRequired( 'req' );
p.addParameter( 'opt1', 1 );
p.parse( req, varargin{:} );
p.Results
end
>> parsertest( 'a', 'req', 'x')
ans =
opt1: 1
req: 'x'
Since 'req' was not specified with addParameter, I would expect this to throw an error rather than req taking on the value 'x'.
Another situation I would think would cause an error is if multiple instances of 'req', are supplied. Instead, the last instance wins:
>> parsertest( 'a', 'req', 'x', 'req', 'y', 'req', 'z')
ans =
opt1: 1
req: 'z'
Are these behaviors expected?
1 Comment
jgg
on 27 Jan 2016
Edited: jgg
on 29 Jan 2016
Wow, this is not at all how I expected this would work. It seems that the addParameter name-pair is somehow taking precedence over the required name-pair, despite the name for the required parameter being entirely internal to the input parser object. This definitely looks like a bug to me, especially since I cannot find any option or setting to control this behaviour. Bumping for priority.
EDIT1: I replicated in this R2015A as well, so it's not version specific. I think it's also a security concern, since if you have validation on addRequired but not on addParameter, you could inject values into the "required" value while skipping validation.
Answers (0)
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!