Skip to content

Simplify Union type alias in optuna/samplers/_cmaes.py#6478

Merged
c-bata merged 2 commits intooptuna:masterfrom
roli-lpci:fix/future-annotations-cmaes
Feb 26, 2026
Merged

Simplify Union type alias in optuna/samplers/_cmaes.py#6478
c-bata merged 2 commits intooptuna:masterfrom
roli-lpci:fix/future-annotations-cmaes

Conversation

@roli-lpci
Copy link
Copy Markdown
Contributor

Motivation

Contributes to #4508.

Among the 8 files listed as "cannot be updated" in the issue, _cmaes.py is the only one where the Union usage is exclusively inside a TYPE_CHECKING block (line 35). Since TYPE_CHECKING is False at runtime, the | union syntax is never evaluated by the interpreter — it is only seen by static type checkers, which fully support it regardless of the Python version.

This is distinct from the other remaining files (e.g., _grid.py, _typing.py, distributions.py, probability_distributions.py), where Union appears in runtime type aliases that would fail on Python 3.9 if converted to |.

Description of the changes

  • Replace Union[cmaes.CMA, cmaes.SepCMA, cmaes.CMAwM] with cmaes.CMA | cmaes.SepCMA | cmaes.CMAwM inside the if TYPE_CHECKING: block
  • Remove the now-unused from typing import Union import

roli-lpci and others added 2 commits February 25, 2026 01:54
Replace `Union[cmaes.CMA, cmaes.SepCMA, cmaes.CMAwM]` with the PEP 604
`cmaes.CMA | cmaes.SepCMA | cmaes.CMAwM` syntax and remove the unused
`from typing import Union` import.

This is safe because the type alias lives inside a `TYPE_CHECKING` block
that is never evaluated at runtime.

Addresses optuna#4508.
mypy does not recognize `X | Y` as a type alias without explicit
TypeAlias annotation, unlike Union[X, Y] which is implicitly treated
as one.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Copy link
Copy Markdown
Member

@c-bata c-bata left a comment

Choose a reason for hiding this comment

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

LGTM. Thank you for your contribution.

@c-bata c-bata merged commit 9ed3f59 into optuna:master Feb 26, 2026
13 checks passed
@c-bata c-bata added the code-fix Change that does not change the behavior, such as code refactoring. label Feb 26, 2026
@c-bata c-bata added this to the v4.8.0 milestone Feb 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

code-fix Change that does not change the behavior, such as code refactoring.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants