Simplify Union type alias in optuna/samplers/_cmaes.py#6478
Merged
c-bata merged 2 commits intooptuna:masterfrom Feb 26, 2026
Merged
Simplify Union type alias in optuna/samplers/_cmaes.py#6478c-bata merged 2 commits intooptuna:masterfrom
c-bata merged 2 commits intooptuna:masterfrom
Conversation
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>
c-bata
approved these changes
Feb 26, 2026
Member
c-bata
left a comment
There was a problem hiding this comment.
LGTM. Thank you for your contribution.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Contributes to #4508.
Among the 8 files listed as "cannot be updated" in the issue,
_cmaes.pyis the only one where theUnionusage is exclusively inside aTYPE_CHECKINGblock (line 35). SinceTYPE_CHECKINGisFalseat 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), whereUnionappears in runtime type aliases that would fail on Python 3.9 if converted to|.Description of the changes
Union[cmaes.CMA, cmaes.SepCMA, cmaes.CMAwM]withcmaes.CMA | cmaes.SepCMA | cmaes.CMAwMinside theif TYPE_CHECKING:blockfrom typing import Unionimport