codeant-ai-for-open-source[bot] commented on code in PR #41028: URL: https://github.com/apache/superset/pull/41028#discussion_r3481348782
########## superset/utils/number_format.py: ########## @@ -0,0 +1,250 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from typing import Any + +from babel.numbers import get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" + +# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format. +SI_PREFIXES = { + -8: "y", + -7: "z", + -6: "a", + -5: "f", + -4: "p", + -3: "n", + -2: "ยต", + -1: "m", + 0: "", + 1: "k", + 2: "M", + 3: "G", + 4: "T", + 5: "P", + 6: "E", + 7: "Z", + 8: "Y", +} + +# d3-format specifier grammar: +# [[fill]align][sign][symbol][0][width][,][.precision][~][type] +D3_FORMAT_RE = re.compile( + r"^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$", + re.IGNORECASE, +) + + +def format_number_with_config( + d3_format: str | None, + currency: dict[str, Any] | None, + value: Any, +) -> Any: + """ + Format ``value`` using a d3-format string and optional currency config. + + :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or ``SMART_NUMBER`` + :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": "prefix"|"suffix"}`` + :param value: the raw value to format + :return: the formatted string, or the value unchanged when it is not a + number that can be formatted + """ + if value is None: + return "" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return value + if math.isnan(value) or math.isinf(value): + return "" + + try: + if currency and currency.get("symbol"): + # the frontend strips the currency symbol from the d3 format and + # falls back to SMART_NUMBER when no explicit format is set + number_format = (d3_format or SMART_NUMBER).replace("$", "") + formatted = format_numeric(number_format, value) + if currency["symbol"] == AUTO_CURRENCY: + return formatted + return apply_currency(formatted, currency) + if not d3_format: + return raw_string(value) + return format_numeric(d3_format, value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + # never let an unexpected value break a whole report table + return raw_string(value) + + +def format_numeric(d3_format: str, value: float) -> str: Review Comment: **Suggestion:** Add a short docstring to this new function describing when it delegates to smart-number formatting versus d3-format formatting. [custom_rule] **Severity Level:** Minor โ ๏ธ <details> <summary><b>Why it matters? ๐ค </b></summary> This is a newly added Python function and it has no docstring in the final file state. The custom rule requires newly added Python functions and classes to include docstrings, so the suggestion correctly identifies a real violation. </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=527dc2bec990409e9dee955f99d4df11&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=527dc2bec990409e9dee955f99d4df11&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent ๐ค </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/utils/number_format.py **Line:** 109:109 **Comment:** *Custom Rule: Add a short docstring to this new function describing when it delegates to smart-number formatting versus d3-format formatting. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=528cc5ef05c1afb20cc87660a710fbab9b094443ac9e4117981fdbbcc849ac0a&reaction=like'>๐</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=528cc5ef05c1afb20cc87660a710fbab9b094443ac9e4117981fdbbcc849ac0a&reaction=dislike'>๐</a> ########## superset/utils/number_format.py: ########## @@ -0,0 +1,250 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from typing import Any + +from babel.numbers import get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" + +# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format. +SI_PREFIXES = { + -8: "y", + -7: "z", + -6: "a", + -5: "f", + -4: "p", + -3: "n", + -2: "ยต", + -1: "m", + 0: "", + 1: "k", + 2: "M", + 3: "G", + 4: "T", + 5: "P", + 6: "E", + 7: "Z", + 8: "Y", +} + +# d3-format specifier grammar: +# [[fill]align][sign][symbol][0][width][,][.precision][~][type] +D3_FORMAT_RE = re.compile( + r"^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$", + re.IGNORECASE, +) + + +def format_number_with_config( + d3_format: str | None, + currency: dict[str, Any] | None, + value: Any, +) -> Any: + """ + Format ``value`` using a d3-format string and optional currency config. + + :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or ``SMART_NUMBER`` + :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": "prefix"|"suffix"}`` + :param value: the raw value to format + :return: the formatted string, or the value unchanged when it is not a + number that can be formatted + """ + if value is None: + return "" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return value + if math.isnan(value) or math.isinf(value): + return "" + + try: + if currency and currency.get("symbol"): + # the frontend strips the currency symbol from the d3 format and + # falls back to SMART_NUMBER when no explicit format is set + number_format = (d3_format or SMART_NUMBER).replace("$", "") + formatted = format_numeric(number_format, value) + if currency["symbol"] == AUTO_CURRENCY: + return formatted + return apply_currency(formatted, currency) + if not d3_format: + return raw_string(value) + return format_numeric(d3_format, value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + # never let an unexpected value break a whole report table + return raw_string(value) + + +def format_numeric(d3_format: str, value: float) -> str: + if d3_format in (SMART_NUMBER, SMART_NUMBER_SIGNED): + return format_smart_number(value, signed=d3_format == SMART_NUMBER_SIGNED) + return format_d3(d3_format, value) + + +def format_d3(d3_format: str, value: float) -> str: + match = D3_FORMAT_RE.match(d3_format) + if not match: + raise ValueError(d3_format) + + sign = "+" if match.group(3) == "+" else "" + currency_symbol = match.group(4) == "$" + comma = "," if match.group(7) else "" + precision = int(match.group(8)) if match.group(8) is not None else None + trim = bool(match.group(9)) + type_ = (match.group(10) or "").lower() + + if type_ == "s": + formatted = format_si(value, precision if precision is not None else 6, trim) + elif type_ == "r": + formatted = format_significant( + value, precision if precision is not None else 6, trim, sign, comma + ) + else: + if type_ == "d": + formatted = format(int(quantize_half_up(value, 0)), f"{sign}{comma}d") + else: + decimals = f".{precision}" if precision is not None else "" + formatted = format(value, f"{sign}{comma}{decimals}{type_}") + formatted = normalize_exponent(formatted) + formatted = trim_trailing_zeros(formatted) if trim else formatted + + if currency_symbol: + formatted = prepend_currency_symbol(formatted) + return formatted + + +def format_smart_number(value: float, signed: bool = False) -> str: Review Comment: **Suggestion:** Add a docstring to this newly added function to explain threshold rules and signed output behavior. [custom_rule] **Severity Level:** Minor โ ๏ธ <details> <summary><b>Why it matters? ๐ค </b></summary> The function is newly added and there is no docstring above it. Since the rule requires newly added Python functions to be documented inline, this is a real violation. </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=47e0ae83c9cd46bcaccf5a432a4a09f7&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=47e0ae83c9cd46bcaccf5a432a4a09f7&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent ๐ค </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/utils/number_format.py **Line:** 147:147 **Comment:** *Custom Rule: Add a docstring to this newly added function to explain threshold rules and signed output behavior. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=97606befbc07cefc6a7d79a3ead8ede29a7948bfef1f31664b43a58ec190a253&reaction=like'>๐</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=97606befbc07cefc6a7d79a3ead8ede29a7948bfef1f31664b43a58ec190a253&reaction=dislike'>๐</a> ########## superset/utils/number_format.py: ########## @@ -0,0 +1,250 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from typing import Any + +from babel.numbers import get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" + +# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format. +SI_PREFIXES = { + -8: "y", + -7: "z", + -6: "a", + -5: "f", + -4: "p", + -3: "n", + -2: "ยต", + -1: "m", + 0: "", + 1: "k", + 2: "M", + 3: "G", + 4: "T", + 5: "P", + 6: "E", + 7: "Z", + 8: "Y", +} + +# d3-format specifier grammar: +# [[fill]align][sign][symbol][0][width][,][.precision][~][type] +D3_FORMAT_RE = re.compile( + r"^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$", + re.IGNORECASE, +) + + +def format_number_with_config( + d3_format: str | None, + currency: dict[str, Any] | None, + value: Any, +) -> Any: + """ + Format ``value`` using a d3-format string and optional currency config. + + :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or ``SMART_NUMBER`` + :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": "prefix"|"suffix"}`` + :param value: the raw value to format + :return: the formatted string, or the value unchanged when it is not a + number that can be formatted + """ + if value is None: + return "" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return value + if math.isnan(value) or math.isinf(value): + return "" + + try: + if currency and currency.get("symbol"): + # the frontend strips the currency symbol from the d3 format and + # falls back to SMART_NUMBER when no explicit format is set + number_format = (d3_format or SMART_NUMBER).replace("$", "") + formatted = format_numeric(number_format, value) + if currency["symbol"] == AUTO_CURRENCY: + return formatted + return apply_currency(formatted, currency) + if not d3_format: + return raw_string(value) + return format_numeric(d3_format, value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + # never let an unexpected value break a whole report table + return raw_string(value) + + +def format_numeric(d3_format: str, value: float) -> str: + if d3_format in (SMART_NUMBER, SMART_NUMBER_SIGNED): + return format_smart_number(value, signed=d3_format == SMART_NUMBER_SIGNED) + return format_d3(d3_format, value) + + +def format_d3(d3_format: str, value: float) -> str: Review Comment: **Suggestion:** Add a docstring to this new function explaining the supported d3 specifier parts and the expected output behavior. [custom_rule] **Severity Level:** Minor โ ๏ธ <details> <summary><b>Why it matters? ๐ค </b></summary> This function is newly introduced and does not have an inline docstring in the final file state. That directly violates the rule requiring docstrings for newly added Python functions. </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=ecef6984bd8845558e1502901bd53a58&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=ecef6984bd8845558e1502901bd53a58&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent ๐ค </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/utils/number_format.py **Line:** 115:115 **Comment:** *Custom Rule: Add a docstring to this new function explaining the supported d3 specifier parts and the expected output behavior. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=6ed7ba8e49dce30e200b01d1dd3da165d310b3b3a28078b8a0662d133926df5d&reaction=like'>๐</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=6ed7ba8e49dce30e200b01d1dd3da165d310b3b3a28078b8a0662d133926df5d&reaction=dislike'>๐</a> ########## superset/utils/number_format.py: ########## @@ -0,0 +1,250 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from typing import Any + +from babel.numbers import get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" + +# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format. +SI_PREFIXES = { + -8: "y", + -7: "z", + -6: "a", + -5: "f", + -4: "p", + -3: "n", + -2: "ยต", + -1: "m", + 0: "", + 1: "k", + 2: "M", + 3: "G", + 4: "T", + 5: "P", + 6: "E", + 7: "Z", + 8: "Y", +} + +# d3-format specifier grammar: +# [[fill]align][sign][symbol][0][width][,][.precision][~][type] +D3_FORMAT_RE = re.compile( + r"^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$", + re.IGNORECASE, +) + + +def format_number_with_config( + d3_format: str | None, + currency: dict[str, Any] | None, + value: Any, +) -> Any: + """ + Format ``value`` using a d3-format string and optional currency config. + + :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or ``SMART_NUMBER`` + :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": "prefix"|"suffix"}`` + :param value: the raw value to format + :return: the formatted string, or the value unchanged when it is not a + number that can be formatted + """ + if value is None: + return "" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return value + if math.isnan(value) or math.isinf(value): + return "" + + try: + if currency and currency.get("symbol"): + # the frontend strips the currency symbol from the d3 format and + # falls back to SMART_NUMBER when no explicit format is set + number_format = (d3_format or SMART_NUMBER).replace("$", "") + formatted = format_numeric(number_format, value) + if currency["symbol"] == AUTO_CURRENCY: + return formatted + return apply_currency(formatted, currency) + if not d3_format: + return raw_string(value) + return format_numeric(d3_format, value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + # never let an unexpected value break a whole report table + return raw_string(value) + + +def format_numeric(d3_format: str, value: float) -> str: + if d3_format in (SMART_NUMBER, SMART_NUMBER_SIGNED): + return format_smart_number(value, signed=d3_format == SMART_NUMBER_SIGNED) + return format_d3(d3_format, value) + + +def format_d3(d3_format: str, value: float) -> str: + match = D3_FORMAT_RE.match(d3_format) + if not match: + raise ValueError(d3_format) + + sign = "+" if match.group(3) == "+" else "" + currency_symbol = match.group(4) == "$" + comma = "," if match.group(7) else "" + precision = int(match.group(8)) if match.group(8) is not None else None + trim = bool(match.group(9)) + type_ = (match.group(10) or "").lower() + + if type_ == "s": + formatted = format_si(value, precision if precision is not None else 6, trim) + elif type_ == "r": + formatted = format_significant( + value, precision if precision is not None else 6, trim, sign, comma + ) + else: + if type_ == "d": + formatted = format(int(quantize_half_up(value, 0)), f"{sign}{comma}d") + else: + decimals = f".{precision}" if precision is not None else "" + formatted = format(value, f"{sign}{comma}{decimals}{type_}") + formatted = normalize_exponent(formatted) + formatted = trim_trailing_zeros(formatted) if trim else formatted + + if currency_symbol: + formatted = prepend_currency_symbol(formatted) + return formatted + + +def format_smart_number(value: float, signed: bool = False) -> str: + if value == 0: + body = "0" + else: + absolute = abs(value) + if absolute >= 1000: + body = format_si(value, 3, trim=True, billions=True) + elif absolute >= 1: + body = trim_trailing_zeros(format(value, ".2f")) + elif absolute >= 0.001: + body = trim_trailing_zeros(format(value, ".4f")) + elif absolute > 0.000001: + body = format_si(value * 1000000, 3, trim=True) + "ยต" + else: + body = format_si(value, 3, trim=True) + prefix = "+" if signed and value > 0 else "" + return prefix + body + + +def format_si(value: float, precision: int, trim: bool, billions: bool = False) -> str: Review Comment: **Suggestion:** Add a concise docstring describing how SI prefix scaling works and what the `billions` flag changes. [custom_rule] **Severity Level:** Minor โ ๏ธ <details> <summary><b>Why it matters? ๐ค </b></summary> This is a new Python function in the added file and it lacks a docstring. That matches the custom rule for newly added functions needing inline documentation. </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=01f71546eb7b4fffa99c9c2170ab379c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=01f71546eb7b4fffa99c9c2170ab379c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent ๐ค </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/utils/number_format.py **Line:** 166:166 **Comment:** *Custom Rule: Add a concise docstring describing how SI prefix scaling works and what the `billions` flag changes. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=f75095f4db788a6527b23546f95e00ee320d0a6d6058d99840584b1aaeb37aa2&reaction=like'>๐</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=f75095f4db788a6527b23546f95e00ee320d0a6d6058d99840584b1aaeb37aa2&reaction=dislike'>๐</a> ########## superset/utils/number_format.py: ########## @@ -0,0 +1,250 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +""" +Server-side port of the d3-format based number and currency formatters used by +the Table and Pivot Table chart plugins. + +Report notifications that embed a chart as text build the table in Python and +have no access to the frontend formatters, so chart number/currency format +configuration has to be reproduced here to render the same values an end user +sees in the browser. +""" + +from __future__ import annotations + +import math +import re +from decimal import Decimal, ROUND_HALF_UP +from typing import Any + +from babel.numbers import get_currency_symbol + +SMART_NUMBER = "SMART_NUMBER" +SMART_NUMBER_SIGNED = "SMART_NUMBER_SIGNED" +AUTO_CURRENCY = "AUTO" + +LOCALE = "en_US" + +# SI prefixes keyed by their power-of-1000 exponent, mirroring d3-format. +SI_PREFIXES = { + -8: "y", + -7: "z", + -6: "a", + -5: "f", + -4: "p", + -3: "n", + -2: "ยต", + -1: "m", + 0: "", + 1: "k", + 2: "M", + 3: "G", + 4: "T", + 5: "P", + 6: "E", + 7: "Z", + 8: "Y", +} + +# d3-format specifier grammar: +# [[fill]align][sign][symbol][0][width][,][.precision][~][type] +D3_FORMAT_RE = re.compile( + r"^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(?:\.(\d+))?(~)?([a-z%])?$", + re.IGNORECASE, +) + + +def format_number_with_config( + d3_format: str | None, + currency: dict[str, Any] | None, + value: Any, +) -> Any: + """ + Format ``value`` using a d3-format string and optional currency config. + + :param d3_format: a d3-format specifier (e.g. ``",.2f"``) or ``SMART_NUMBER`` + :param currency: ``{"symbol": <ISO 4217>, "symbolPosition": "prefix"|"suffix"}`` + :param value: the raw value to format + :return: the formatted string, or the value unchanged when it is not a + number that can be formatted + """ + if value is None: + return "" + if isinstance(value, bool) or not isinstance(value, (int, float)): + return value + if math.isnan(value) or math.isinf(value): + return "" + + try: + if currency and currency.get("symbol"): + # the frontend strips the currency symbol from the d3 format and + # falls back to SMART_NUMBER when no explicit format is set + number_format = (d3_format or SMART_NUMBER).replace("$", "") + formatted = format_numeric(number_format, value) + if currency["symbol"] == AUTO_CURRENCY: + return formatted + return apply_currency(formatted, currency) + if not d3_format: + return raw_string(value) + return format_numeric(d3_format, value) + except Exception: # pylint: disable=broad-except # noqa: BLE001 + # never let an unexpected value break a whole report table + return raw_string(value) + + +def format_numeric(d3_format: str, value: float) -> str: + if d3_format in (SMART_NUMBER, SMART_NUMBER_SIGNED): + return format_smart_number(value, signed=d3_format == SMART_NUMBER_SIGNED) + return format_d3(d3_format, value) + + +def format_d3(d3_format: str, value: float) -> str: + match = D3_FORMAT_RE.match(d3_format) + if not match: + raise ValueError(d3_format) + + sign = "+" if match.group(3) == "+" else "" + currency_symbol = match.group(4) == "$" + comma = "," if match.group(7) else "" + precision = int(match.group(8)) if match.group(8) is not None else None + trim = bool(match.group(9)) + type_ = (match.group(10) or "").lower() + + if type_ == "s": + formatted = format_si(value, precision if precision is not None else 6, trim) + elif type_ == "r": + formatted = format_significant( + value, precision if precision is not None else 6, trim, sign, comma + ) + else: + if type_ == "d": + formatted = format(int(quantize_half_up(value, 0)), f"{sign}{comma}d") + else: + decimals = f".{precision}" if precision is not None else "" + formatted = format(value, f"{sign}{comma}{decimals}{type_}") + formatted = normalize_exponent(formatted) + formatted = trim_trailing_zeros(formatted) if trim else formatted + + if currency_symbol: + formatted = prepend_currency_symbol(formatted) + return formatted + + +def format_smart_number(value: float, signed: bool = False) -> str: + if value == 0: + body = "0" + else: + absolute = abs(value) + if absolute >= 1000: + body = format_si(value, 3, trim=True, billions=True) + elif absolute >= 1: + body = trim_trailing_zeros(format(value, ".2f")) + elif absolute >= 0.001: + body = trim_trailing_zeros(format(value, ".4f")) + elif absolute > 0.000001: + body = format_si(value * 1000000, 3, trim=True) + "ยต" + else: + body = format_si(value, 3, trim=True) + prefix = "+" if signed and value > 0 else "" + return prefix + body + + +def format_si(value: float, precision: int, trim: bool, billions: bool = False) -> str: + if value == 0: + return format_significant(0.0, precision, trim) + + exponent = max(-8, min(8, math.floor(math.log10(abs(value))) // 3)) + mantissa = value / (10 ** (exponent * 3)) + # rounding can push the mantissa up to the next SI bracket (e.g. 999.5k) + if abs(round_to_significant(mantissa, precision)) >= 1000 and exponent < 8: + exponent += 1 + mantissa = value / (10 ** (exponent * 3)) + + symbol = SI_PREFIXES[exponent] + if billions and symbol == "G": + symbol = "B" + + return format_significant(mantissa, precision, trim) + symbol + + +def format_significant( + value: float, precision: int, trim: bool, sign: str = "", comma: str = "" +) -> str: + """ + Format to `precision` significant digits in fixed-point notation. + + Serves both the d3 `r` type and SI mantissas, and avoids the scientific + notation Python's `g` would switch to. + """ + rounded = round_to_significant(value, precision) + decimals = decimals_for_significant(rounded, precision) + formatted = format(rounded, f"{sign}{comma}.{decimals}f") + return trim_trailing_zeros(formatted) if trim else formatted + + +def round_to_significant(value: float, precision: int) -> float: Review Comment: **Suggestion:** Add a docstring to this new helper to clarify how significant-digit rounding is computed. [custom_rule] **Severity Level:** Minor โ ๏ธ <details> <summary><b>Why it matters? ๐ค </b></summary> The function is newly introduced and has no docstring in the final code. This is a valid instance of the docstring rule violation for new Python functions. </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c1697c8179694b0e81dd54bfe3ebcd1b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c1697c8179694b0e81dd54bfe3ebcd1b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent ๐ค </b></summary> ```mdx This is a comment left during a code review. **Path:** superset/utils/number_format.py **Line:** 199:199 **Comment:** *Custom Rule: Add a docstring to this new helper to clarify how significant-digit rounding is computed. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=a71b222993ef9399112d3f204a9a74c4071fe71a9970a511d1c25c4577e64e0c&reaction=like'>๐</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41028&comment_hash=a71b222993ef9399112d3f204a9a74c4071fe71a9970a511d1c25c4577e64e0c&reaction=dislike'>๐</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
