Skip to content

Conversation

@3015pavan
Copy link

@3015pavan 3015pavan commented Nov 17, 2025

This commit implements a new configuration option default-group-optionality that allows users to treat all dependency groups as optional by default.

When set to true, Poetry will only install the implicit main group by default, and other groups must be explicitly requested using --with or --only flags. This eliminates the need to mark each group as optional = true in pyproject.toml for projects with many optional dependency groups.

Changes:

  • Add default-group-optionality boolean config option (default: false)
  • Modify GroupCommand.non_optional_groups to respect the configuration
  • Add comprehensive tests for the new functionality
  • Update documentation with usage examples

Fixes #10550

Pull Request Check List

Resolves: #issue-number-here

  • Added tests for changed code.
  • Updated documentation for changed code.

Summary by Sourcery

Add a new default-group-optionality configuration option to allow treating all dependency groups as optional by default and update related command logic, documentation, and tests.

New Features:

  • Introduce default-group-optionality boolean config option to toggle default optionality of dependency groups

Enhancements:

  • Update GroupCommand to respect the default-group-optionality setting when determining which groups to install

Documentation:

  • Document the default-group-optionality option in the configuration guide with usage examples

Tests:

  • Add comprehensive tests for the new default-group-optionality behavior, including install scenarios and config commands

This commit implements a new configuration option `default-group-optionality`
that allows users to treat all dependency groups as optional by default.

When set to `true`, Poetry will only install the implicit `main` group by
default, and other groups must be explicitly requested using `--with` or
`--only` flags. This eliminates the need to mark each group as `optional = true`
in pyproject.toml for projects with many optional dependency groups.

Changes:
- Add `default-group-optionality` boolean config option (default: false)
- Modify GroupCommand.non_optional_groups to respect the configuration
- Add comprehensive tests for the new functionality
- Update documentation with usage examples

Fixes python-poetry#10550
@sourcery-ai
Copy link

sourcery-ai bot commented Nov 17, 2025

Reviewer's Guide

Introduces a new default-group-optionality boolean setting that makes all dependency groups optional by default, updates GroupCommand to respect this option, extends configuration handling and documentation, and adds tests covering the new behavior.

Class diagram for updated configuration handling (Config class)

classDiagram
    class Config {
        +bool default-group-optionality = False
        +__init__(use_environment: bool)
        +_get_normalizer(name: str)
    }
Loading

Class diagram for updated GroupCommand logic

classDiagram
    class GroupCommand {
        +non_optional_groups: set[str]
    }
    GroupCommand --> Config : uses
Loading

File-Level Changes

Change Details Files
Introduce default-group-optionality configuration key
  • Add default false value in Config.DEFAULTS
  • Include key in boolean normalizer set
  • Register key in config command validators
src/poetry/config/config.py
src/poetry/console/commands/config.py
Update group command to honor default-group-optionality
  • Fetch config value in non_optional_groups
  • Return empty non-optional set when option is enabled
src/poetry/console/commands/group_command.py
Document the default-group-optionality option
  • Add key description, environment variable, and examples
docs/configuration.md
Add and update tests for default-group-optionality
  • Update config listing and default value tests
  • Add integration tests for install command behavior
tests/console/commands/test_config.py
tests/config/test_config.py
tests/console/commands/test_default_group_optionality.py

Assessment against linked issues

Issue Objective Addressed Explanation
#10550 Implement a configuration option (e.g., tool.poetry.default-group-optionality) to allow users to set the default optionality for dependency groups.
#10550 Ensure that when the configuration option is enabled, all dependency groups (except the implicit main group) are treated as optional by default, so that only explicitly requested groups are installed.
#10550 Update documentation and add tests to cover the new configuration option and its behavior.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey there - I've reviewed your changes - here's some feedback:

  • The non_optional_groups override currently treats every group as optional when default-group-optionality is true—consider preserving any explicit optional = false declarations in pyproject.toml so users can still force non-optional groups.
  • Per the existing TODO, it would be cleaner to move the default-group-optionality logic out of the console command and into poetry-core to centralize dependency-group handling.
  • The documentation examples don’t specify --local or --global when setting the config—consider clarifying which scope is used in those examples for better user guidance.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The non_optional_groups override currently treats every group as optional when default-group-optionality is true—consider preserving any explicit optional = false declarations in pyproject.toml so users can still force non-optional groups.
- Per the existing TODO, it would be cleaner to move the default-group-optionality logic out of the console command and into poetry-core to centralize dependency-group handling.
- The documentation examples don’t specify --local or --global when setting the config—consider clarifying which scope is used in those examples for better user guidance.

## Individual Comments

### Comment 1
<location> `tests/console/commands/test_default_group_optionality.py:112-136` </location>
<code_context>
+    assert installer_groups == {MAIN_GROUP}
+
+
+def test_with_default_group_optionality_and_with_option(
+    install_tester: CommandTester, mocker: MockerFixture
+) -> None:
+    """
+    With default-group-optionality enabled, --with can explicitly include groups.
+    """
+    # Enable the configuration
+    install_tester.command.poetry.config.merge({"default-group-optionality": True})
+
+    mocker.patch.object(install_tester.command.installer, "run", return_value=0)
+    mocker.patch(
+        "poetry.masonry.builders.editable.EditableBuilder",
+        side_effect=Exception("Should not be called"),
+    )
+
+    status_code = install_tester.execute("--no-root --with test,dev")
+    assert status_code == 0
+
+    # Should install main, test, and dev groups
+    installer_groups = set(install_tester.command.installer._groups or [])
+    assert installer_groups == {MAIN_GROUP, "test", "dev"}
+
+
</code_context>

<issue_to_address>
**suggestion (testing):** Missing test for invalid group names in --with option.

Add a test case using --with with a non-existent group name to confirm the CLI handles invalid input correctly, such as raising an error or ignoring unknown groups.

```suggestion
+
+
def test_with_default_group_optionality_and_with_option(
    install_tester: CommandTester, mocker: MockerFixture
) -> None:
    """
    With default-group-optionality enabled, --with can explicitly include groups.
    """
    # Enable the configuration
    install_tester.command.poetry.config.merge({"default-group-optionality": True})

    mocker.patch.object(install_tester.command.installer, "run", return_value=0)
    mocker.patch(
        "poetry.masonry.builders.editable.EditableBuilder",
        side_effect=Exception("Should not be called"),
    )

    status_code = install_tester.execute("--no-root --with test,dev")
    assert status_code == 0

    # Should install main, test, and dev groups
    installer_groups = set(install_tester.command.installer._groups or [])
    assert installer_groups == {MAIN_GROUP, "test", "dev"}


def test_with_default_group_optionality_and_invalid_group(
    install_tester: "CommandTester", mocker: "MockerFixture"
) -> None:
    """
    Using --with with a non-existent group name should result in an error.
    """
    # Enable the configuration
    install_tester.command.poetry.config.merge({"default-group-optionality": True})

    mocker.patch.object(install_tester.command.installer, "run", return_value=0)
    mocker.patch(
        "poetry.masonry.builders.editable.EditableBuilder",
        side_effect=Exception("Should not be called"),
    )

    # Use a non-existent group name
    status_code = install_tester.execute("--no-root --with test,nonexistentgroup")
    # Should return a non-zero status code indicating error
    assert status_code != 0

    # Optionally, check for error message about unknown group
    output = install_tester.io.fetch_error()
    assert "nonexistentgroup" in output
    assert "Unknown dependency group" in output or "does not exist" in output
```
</issue_to_address>

### Comment 2
<location> `tests/console/commands/test_default_group_optionality.py:136-158` </location>
<code_context>
+    assert installer_groups == {MAIN_GROUP, "test", "dev"}
+
+
+def test_with_default_group_optionality_and_only_option(
+    install_tester: CommandTester, mocker: MockerFixture
+) -> None:
+    """
+    With default-group-optionality enabled, --only still works as expected.
+    """
+    # Enable the configuration
+    install_tester.command.poetry.config.merge({"default-group-optionality": True})
+
+    mocker.patch.object(install_tester.command.installer, "run", return_value=0)
+    mocker.patch(
+        "poetry.masonry.builders.editable.EditableBuilder",
+        side_effect=Exception("Should not be called"),
+    )
+
+    status_code = install_tester.execute("--no-root --only test")
+    assert status_code == 0
+
+    # Should only install test group
+    installer_groups = set(install_tester.command.installer._groups or [])
+    assert installer_groups == {"test"}
+
+
</code_context>

<issue_to_address>
**suggestion (testing):** Missing test for combining --only and --with flags.

Please add a test case that uses both --only and --with flags together with default-group-optionality enabled to confirm their combined behavior.

```suggestion

def test_with_default_group_optionality_and_only_and_with_flags(
    install_tester: "CommandTester", mocker: "MockerFixture"
) -> None:
    """
    With default-group-optionality enabled, using --only and --with together
    should only install the group specified by --only.
    """
    # Enable the configuration
    install_tester.command.poetry.config.merge({"default-group-optionality": True})

    mocker.patch.object(install_tester.command.installer, "run", return_value=0)
    mocker.patch(
        "poetry.masonry.builders.editable.EditableBuilder",
        side_effect=Exception("Should not be called"),
    )

    status_code = install_tester.execute("--no-root --only test --with dev")
    assert status_code == 0

    # Should only install test group, --with should not add dev when --only is present
    installer_groups = set(install_tester.command.installer._groups or [])
    assert installer_groups == {"test"}

```
</issue_to_address>

### Comment 3
<location> `tests/console/commands/test_default_group_optionality.py:169-178` </location>
<code_context>
+    assert "false" in config_tester.io.fetch_output().strip().lower()
+
+
+def test_config_set_default_group_optionality(config_tester: CommandTester) -> None:
+    """
+    Test setting the default-group-optionality configuration value.
+    """
+    config_tester.execute("--local default-group-optionality true")
+    assert config_tester.status_code == 0
+
+    config_tester.io.clear_output()
+    config_tester.execute("--local default-group-optionality")
+    assert config_tester.status_code == 0
+    assert "true" in config_tester.io.fetch_output().strip().lower()
+
+
</code_context>

<issue_to_address>
**suggestion (testing):** Missing test for invalid config value types.

Add a test that sets default-group-optionality to an invalid type (e.g., a string or integer) to verify that the system rejects it and returns an appropriate error message.

Suggested implementation:

```python

def test_config_set_default_group_optionality_invalid_type(config_tester: CommandTester) -> None:
    """
    Test setting the default-group-optionality configuration value to an invalid type.
    """
    # Try setting to a string that is not a boolean
    config_tester.execute("--local default-group-optionality notabool")
    assert config_tester.status_code != 0
    assert "invalid" in config_tester.io.fetch_error().strip().lower() or "error" in config_tester.io.fetch_error().strip().lower()

    config_tester.io.clear_error()
    # Try setting to an integer
    config_tester.execute("--local default-group-optionality 123")
    assert config_tester.status_code != 0
    assert "invalid" in config_tester.io.fetch_error().strip().lower() or "error" in config_tester.io.fetch_error().strip().lower()


from typing import TYPE_CHECKING

import pytest

from poetry.core.packages.dependency_group import MAIN_GROUP

```

If your test framework or CLI does not use `fetch_error()` for error output, replace it with the appropriate method to fetch error messages. Also, ensure that the error message contains "invalid" or "error"—adjust the assertion string as needed to match your actual error output.
</issue_to_address>

### Comment 4
<location> `tests/console/commands/test_default_group_optionality.py:15` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Don't import test modules. ([`dont-import-test-modules`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/dont-import-test-modules))

<details><summary>Explanation</summary>Don't import test modules.

Tests should be self-contained and don't depend on each other.

If a helper function is used by multiple tests,
define it in a helper module,
instead of importing one test from the other.
</details>
</issue_to_address>

### Comment 5
<location> `tests/console/commands/test_default_group_optionality.py:16` </location>
<code_context>

</code_context>

<issue_to_address>
**issue (code-quality):** Don't import test modules. ([`dont-import-test-modules`](https://docs.sourcery.ai/Reference/Rules-and-In-Line-Suggestions/Python/Default-Rules/dont-import-test-modules))

<details><summary>Explanation</summary>Don't import test modules.

Tests should be self-contained and don't depend on each other.

If a helper function is used by multiple tests,
define it in a helper module,
instead of importing one test from the other.
</details>
</issue_to_address>

### Comment 6
<location> `src/poetry/console/commands/group_command.py:48-50` </location>
<code_context>
    @property
    def non_optional_groups(self) -> set[str]:
        # TODO: this should move into poetry-core
        default_optional = self.poetry.config.get("default-group-optionality", False)
        if default_optional:
            # When default-group-optionality is True, all groups are optional
            return set()
        return {
            group.name
            for group in self.poetry.package._dependency_groups.values()
            if not group.is_optional()
        }

</code_context>

<issue_to_address>
**suggestion (code-quality):** Use named expression to simplify assignment and conditional ([`use-named-expression`](https://docs.sourcery.ai/Reference/Default-Rules/refactorings/use-named-expression/))

```suggestion
        if default_optional := self.poetry.config.get(
            "default-group-optionality", False
        ):
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 48 to +50
# TODO: this should move into poetry-core
default_optional = self.poetry.config.get("default-group-optionality", False)
if default_optional:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Use named expression to simplify assignment and conditional (use-named-expression)

Suggested change
# TODO: this should move into poetry-core
default_optional = self.poetry.config.get("default-group-optionality", False)
if default_optional:
if default_optional := self.poetry.config.get(
"default-group-optionality", False
):

@3015pavan
Copy link
Author

Hey! I saw issue #10550 and thought this would be useful. Let me know if you'd like any changes! 😊

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

Successfully merging this pull request may close these issues.

Allow setting default optionality for dependency groups

1 participant