Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support default for arguments with multiple values #2164

Open
tekumara opened this issue Dec 31, 2021 · 1 comment
Open

Support default for arguments with multiple values #2164

tekumara opened this issue Dec 31, 2021 · 1 comment

Comments

@tekumara
Copy link

tekumara commented Dec 31, 2021

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

@j7an
Copy link

j7an commented May 21, 2024

@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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants