click icon indicating copy to clipboard operation
click copied to clipboard

Support default for arguments with multiple values

Open tekumara opened this issue 3 years ago • 2 comments

I'd like to be able to specify a default for arguments with multiple values.

A currently failing test case:

import pytest
import click
from click.testing import CliRunner

@pytest.fixture(scope="function")
def runner(request):
    return CliRunner()

def test_multivalue_args_with_default(runner):
    @click.command()
    @click.argument('files', nargs=-1, default=['arg1'])
    def cmd(files):
        for filename in files:
            click.echo(filename)

    result = runner.invoke(cmd, ['--'])
    assert result.output == 'arg1\n'

Fails with:

TypeError: 'default' is not supported for nargs=-1.

I'm using click 8.0.3

tekumara avatar Dec 31 '21 01:12 tekumara

@tekumara The issue with the code lies in the use of the default argument with click.argument. According to Click's documentation, the default argument is not supported for click.argument, but it is supported for click.option. Therefore, the attempt to set a default value for an argument directly leads to unexpected behavior.

To fix this, you should handle the default value within the command function itself.

import pytest
import click
from click.testing import CliRunner

@pytest.fixture(scope="function")
def runner():
    return CliRunner()

def test_multivalue_args_with_default(runner):
    @click.command()
    @click.argument('files', nargs=-1)
    def cmd(files):
        if not files:
            files = ['arg1']
        for filename in files:
            click.echo(filename)

    result = runner.invoke(cmd, ['--'])
    assert result.output == 'arg1\n'

if __name__ == "__main__":
    pytest.main()

In this version, if no files are provided, the command function sets files to ['arg1'], achieving the same effect as trying to set a default value.

j7an avatar May 21 '24 20:05 j7an

Will fix when rewrite parameter docs to show what the parameter class brings vs the option and argument sub classes.

Rowlando13 avatar Feb 02 '25 07:02 Rowlando13

I'd like to be able to specify a default for arguments with multiple values.

@tekumara This has now been fixed in #3030: arguments with nargs=-1 now accepts defaults.

I made a unittest out of your falling example at: https://github.com/pallets/click/blob/3bd9e22cb7290b1e592ee1c1ed6050eea2438861/tests/test_arguments.py#L388-L392

kdeldycke avatar Aug 11 '25 09:08 kdeldycke