-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Allow controlling warnings when converting deprecated units to strings #18586
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
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
# Licensed under a 3-clause BSD style license - see LICENSE.rst | ||
|
||
from enum import StrEnum, auto | ||
from typing import Self | ||
|
||
|
||
class DeprecatedUnitAction(StrEnum): | ||
SILENT = auto() | ||
WARN = auto() | ||
RAISE = auto() | ||
CONVERT = auto() | ||
|
||
@classmethod | ||
def _missing_(cls, value) -> Self | None: | ||
raise ValueError( | ||
f"invalid deprecation handling option: {value!r}. Valid options are " | ||
f"{', '.join(repr(opt.value) for opt in cls)}." | ||
) |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,7 +2,7 @@ | |
|
||
import warnings | ||
from collections.abc import Iterable | ||
from typing import ClassVar, Literal | ||
from typing import ClassVar, Literal, assert_never | ||
|
||
import numpy as np | ||
|
||
|
@@ -14,7 +14,8 @@ | |
UnitBase, | ||
get_current_unit_registry, | ||
) | ||
from astropy.units.errors import UnitsWarning | ||
from astropy.units.enums import DeprecatedUnitAction | ||
from astropy.units.errors import UnitsError, UnitsWarning | ||
from astropy.units.typing import UnitPower, UnitScale | ||
from astropy.units.utils import maybe_simple_fraction | ||
from astropy.utils.misc import did_you_mean | ||
|
@@ -135,7 +136,11 @@ def _format_multiline_fraction( | |
|
||
@classmethod | ||
def to_string( | ||
cls, unit: UnitBase, *, fraction: bool | Literal["inline", "multiline"] = True | ||
cls, | ||
unit: UnitBase, | ||
*, | ||
deprecations: DeprecatedUnitAction = DeprecatedUnitAction.WARN, | ||
fraction: bool | Literal["inline", "multiline"] = True, | ||
) -> str: | ||
"""Convert a unit to its string representation. | ||
|
||
|
@@ -145,6 +150,10 @@ def to_string( | |
---------- | ||
unit : |Unit| | ||
The unit to convert. | ||
deprecations : {"warn", "silent", "raise", "convert"}, optional, keyword-only | ||
Whether deprecated units should emit a warning, be handled | ||
silently or raise an error. The "convert" option replaces | ||
the deprecated unit if possible and emits a warning otherwise. | ||
fraction : {False|True|'inline'|'multiline'}, optional | ||
Options are as follows: | ||
|
||
|
@@ -256,15 +265,33 @@ def _did_you_mean_units(cls, unit: str) -> str: | |
return did_you_mean(unit, cls._units, fix=cls._fix_deprecated) | ||
|
||
@classmethod | ||
def _validate_unit(cls, s: str) -> UnitBase: | ||
def _validate_unit( | ||
cls, s: str, deprecations: DeprecatedUnitAction = DeprecatedUnitAction.WARN | ||
) -> UnitBase: | ||
if s in cls._deprecated_units: | ||
alternative = ( | ||
unit.represents if isinstance(unit := cls._units[s], Unit) else None | ||
) | ||
msg = f"The unit {s!r} has been deprecated in the {cls.__name__} standard." | ||
if alternative: | ||
msg += f" Suggested: {cls.to_string(alternative)}." | ||
warnings.warn(msg, UnitsWarning) | ||
|
||
match DeprecatedUnitAction(deprecations): | ||
case DeprecatedUnitAction.CONVERT: | ||
if alternative: | ||
return alternative | ||
warnings.warn( | ||
msg + " It cannot be automatically converted.", UnitsWarning | ||
) | ||
case DeprecatedUnitAction.WARN: | ||
warnings.warn(msg, UnitsWarning) | ||
case DeprecatedUnitAction.RAISE: | ||
raise UnitsError(msg) | ||
case DeprecatedUnitAction.SILENT: | ||
pass | ||
case _: | ||
assert_never(deprecations) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I like it. |
||
|
||
return cls._units[s] | ||
|
||
@classmethod | ||
|
@@ -275,25 +302,32 @@ def _invalid_unit_error_message(cls, unit: str) -> str: | |
) | ||
|
||
@classmethod | ||
def _decompose_to_known_units(cls, unit: CompositeUnit | NamedUnit) -> UnitBase: | ||
def _decompose_to_known_units( | ||
cls, | ||
unit: CompositeUnit | NamedUnit, | ||
deprecations: DeprecatedUnitAction = DeprecatedUnitAction.WARN, | ||
) -> UnitBase: | ||
""" | ||
Partially decomposes a unit so it is only composed of units that | ||
are "known" to a given format. | ||
""" | ||
if isinstance(unit, CompositeUnit): | ||
return CompositeUnit( | ||
unit.scale, | ||
[cls._decompose_to_known_units(base) for base in unit.bases], | ||
[ | ||
cls._decompose_to_known_units(base, deprecations) | ||
for base in unit.bases | ||
], | ||
unit.powers, | ||
_error_check=False, | ||
) | ||
if isinstance(unit, NamedUnit): | ||
name = unit._get_format_name(cls.name) | ||
try: | ||
return cls._validate_unit(name) | ||
return cls._validate_unit(name, deprecations=deprecations) | ||
except KeyError: | ||
if isinstance(unit, Unit): | ||
return cls._decompose_to_known_units(unit._represents) | ||
return cls._decompose_to_known_units(unit._represents, deprecations) | ||
raise ValueError(cls._invalid_unit_error_message(name)) from None | ||
raise TypeError( | ||
f"unit argument must be a 'NamedUnit' or 'CompositeUnit', not {type(unit)}" | ||
|
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
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
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
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
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
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Are strings permitted?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It is best if these options do not differ needlessly from the
parse_strict
options the unit parsing methods have, and those are all strings.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Then are the type annotations correct?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The tests and documentation only use strings.