Skip to content
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

Remove pre Python 3.9 syntax #1185

Merged
merged 2 commits into from
Sep 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions .github/get_pypi_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,14 @@ def get_info(package_name: str = "") -> dict:
::return:: A dict with last_version, url and sha256
"""
if package_name == "":
raise ValueError("Package name not provided.")
msg = "Package name not provided."
raise ValueError(msg)
url = f"https://pypi.org/pypi/{package_name}/json"
print(f"Calling {url}") # noqa: T201
resp = requests.get(url)
if resp.status_code != 200:
raise Exception(f"ERROR calling PyPI ({url}) : {resp}")
msg = f"ERROR calling PyPI ({url}) : {resp}"
raise Exception(msg)
resp = resp.json()
version = resp["info"]["version"]

Expand All @@ -38,19 +40,19 @@ def get_info(package_name: str = "") -> dict:
return {}


def replace_in_file(filepath: str, info: dict):
def replace_in_file(filepath: str, info: dict) -> None:
"""Replace placeholder in meta.yaml by their values.

::filepath:: Path to meta.yaml, with filename.
::info:: Dict with information to populate.
"""
with open(filepath, "rt", encoding="utf-8") as fin:
with open(filepath, encoding="utf-8") as fin:
meta = fin.read()
# Replace with info from PyPi
meta = meta.replace("PYPI_VERSION", info["last_version"])
meta = meta.replace("PYPI_URL", info["url"])
meta = meta.replace("PYPI_SHA256", info["sha256"])
with open(filepath, "wt", encoding="utf-8") as fout:
with open(filepath, "w", encoding="utf-8") as fout:
fout.write(meta)
print(f"File {filepath} has been updated with info from PyPi.") # noqa: T201

Expand All @@ -75,6 +77,7 @@ def replace_in_file(filepath: str, info: dict):
args = parser.parse_args()
info = get_info(args.package)
print( # noqa: T201
"Information of the last published PyPi package :", info["last_version"]
"Information of the last published PyPi package :",
info["last_version"],
)
replace_in_file(args.filename, info)
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

### 41.5.6 [#1185](https://github.com/openfisca/openfisca-core/pull/1185)

#### Technical changes

- Remove pre Python 3.9 syntax.

### 41.5.5 [#1220](https://github.com/openfisca/openfisca-core/pull/1220)

#### Technical changes
Expand Down
8 changes: 4 additions & 4 deletions openfisca_core/commons/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,16 @@

# Official Public API

from .formulas import apply_thresholds, concat, switch # noqa: F401
from .misc import empty_clone, stringify_array # noqa: F401
from .rates import average_rate, marginal_rate # noqa: F401
from .formulas import apply_thresholds, concat, switch
from .misc import empty_clone, stringify_array
from .rates import average_rate, marginal_rate

__all__ = ["apply_thresholds", "concat", "switch"]
__all__ = ["empty_clone", "stringify_array", *__all__]
__all__ = ["average_rate", "marginal_rate", *__all__]

# Deprecated

from .dummy import Dummy # noqa: F401
from .dummy import Dummy

__all__ = ["Dummy", *__all__]
1 change: 0 additions & 1 deletion openfisca_core/commons/dummy.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,3 @@ def __init__(self) -> None:
"and will be removed in the future.",
]
warnings.warn(" ".join(message), DeprecationWarning, stacklevel=2)
pass
22 changes: 8 additions & 14 deletions openfisca_core/commons/formulas.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@


def apply_thresholds(
input: t.Array[numpy.float_],
input: t.Array[numpy.float64],
thresholds: t.ArrayLike[float],
choices: t.ArrayLike[float],
) -> t.Array[numpy.float_]:
) -> t.Array[numpy.float64]:
"""Makes a choice based on an input and thresholds.

From a list of ``choices``, this function selects one of these values
Expand Down Expand Up @@ -38,7 +38,6 @@ def apply_thresholds(
array([10, 10, 15, 15, 20])

"""

condlist: list[Union[t.Array[numpy.bool_], bool]]
condlist = [input <= threshold for threshold in thresholds]

Expand All @@ -47,12 +46,9 @@ def apply_thresholds(
# must be true to return it.
condlist += [True]

assert len(condlist) == len(choices), " ".join(
[
"'apply_thresholds' must be called with the same number of",
"thresholds than choices, or one more choice.",
]
)
assert len(condlist) == len(
choices
), "'apply_thresholds' must be called with the same number of thresholds than choices, or one more choice."

return numpy.select(condlist, choices)

Expand All @@ -78,7 +74,6 @@ def concat(
array(['this1.0', 'that2.5']...)

"""

if isinstance(this, numpy.ndarray) and not numpy.issubdtype(this.dtype, numpy.str_):
this = this.astype("str")

Expand All @@ -89,9 +84,9 @@ def concat(


def switch(
conditions: t.Array[numpy.float_],
conditions: t.Array[numpy.float64],
value_by_condition: Mapping[float, float],
) -> t.Array[numpy.float_]:
) -> t.Array[numpy.float64]:
"""Mimicks a switch statement.

Given an array of conditions, returns an array of the same size,
Expand All @@ -115,11 +110,10 @@ def switch(
array([80, 80, 80, 90])

"""

assert (
len(value_by_condition) > 0
), "'switch' must be called with at least one value."

condlist = [conditions == condition for condition in value_by_condition.keys()]
condlist = [conditions == condition for condition in value_by_condition]

return numpy.select(condlist, tuple(value_by_condition.values()))
4 changes: 1 addition & 3 deletions openfisca_core/commons/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ def empty_clone(original: T) -> T:
True

"""

Dummy: object
new: T

Expand Down Expand Up @@ -60,7 +59,7 @@ def stringify_array(array: Optional[t.Array[numpy.generic]]) -> str:
>>> stringify_array(None)
'None'

>>> array = numpy.array([10, 20.])
>>> array = numpy.array([10, 20.0])
>>> stringify_array(array)
'[10.0, 20.0]'

Expand All @@ -73,7 +72,6 @@ def stringify_array(array: Optional[t.Array[numpy.generic]]) -> str:
"[<class 'list'>, {}, <function stringify_array...]"

"""

if array is None:
return "None"

Expand Down
20 changes: 9 additions & 11 deletions openfisca_core/commons/rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@


def average_rate(
target: Array[numpy.float_],
target: Array[numpy.float64],
varying: ArrayLike[float],
trim: Optional[ArrayLike[float]] = None,
) -> Array[numpy.float_]:
) -> Array[numpy.float64]:
"""Computes the average rate of a target net income.

Given a ``target`` net income, and according to the ``varying`` gross
Expand All @@ -35,13 +35,12 @@ def average_rate(
Examples:
>>> target = numpy.array([1, 2, 3])
>>> varying = [2, 2, 2]
>>> trim = [-1, .25]
>>> trim = [-1, 0.25]
>>> average_rate(target, varying, trim)
array([ nan, 0. , -0.5])

"""

average_rate: Array[numpy.float_]
average_rate: Array[numpy.float64]

average_rate = 1 - target / varying

Expand All @@ -62,10 +61,10 @@ def average_rate(


def marginal_rate(
target: Array[numpy.float_],
varying: Array[numpy.float_],
target: Array[numpy.float64],
varying: Array[numpy.float64],
trim: Optional[ArrayLike[float]] = None,
) -> Array[numpy.float_]:
) -> Array[numpy.float64]:
"""Computes the marginal rate of a target net income.

Given a ``target`` net income, and according to the ``varying`` gross
Expand All @@ -91,13 +90,12 @@ def marginal_rate(
Examples:
>>> target = numpy.array([1, 2, 3])
>>> varying = numpy.array([1, 2, 4])
>>> trim = [.25, .75]
>>> trim = [0.25, 0.75]
>>> marginal_rate(target, varying, trim)
array([nan, 0.5])

"""

marginal_rate: Array[numpy.float_]
marginal_rate: Array[numpy.float64]

marginal_rate = +1 - (target[:-1] - target[1:]) / (varying[:-1] - varying[1:])

Expand Down
3 changes: 1 addition & 2 deletions openfisca_core/commons/tests/test_dummy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
from openfisca_core.commons import Dummy


def test_dummy_deprecation():
def test_dummy_deprecation() -> None:
"""Dummy throws a deprecation warning when instantiated."""

with pytest.warns(DeprecationWarning):
assert Dummy()
21 changes: 7 additions & 14 deletions openfisca_core/commons/tests/test_formulas.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
from openfisca_core import commons


def test_apply_thresholds_when_several_inputs():
def test_apply_thresholds_when_several_inputs() -> None:
"""Makes a choice for any given input."""

input_ = numpy.array([4, 5, 6, 7, 8, 9, 10])
thresholds = [5, 7, 9]
choices = [10, 15, 20, 25]
Expand All @@ -17,9 +16,8 @@ def test_apply_thresholds_when_several_inputs():
assert_array_equal(result, [10, 10, 15, 15, 20, 20, 25])


def test_apply_thresholds_when_too_many_thresholds():
def test_apply_thresholds_when_too_many_thresholds() -> None:
"""Raises an AssertionError when thresholds > choices."""

input_ = numpy.array([6])
thresholds = [5, 7, 9, 11]
choices = [10, 15, 20]
Expand All @@ -28,9 +26,8 @@ def test_apply_thresholds_when_too_many_thresholds():
assert commons.apply_thresholds(input_, thresholds, choices)


def test_apply_thresholds_when_too_many_choices():
def test_apply_thresholds_when_too_many_choices() -> None:
"""Raises an AssertionError when thresholds < choices - 1."""

input_ = numpy.array([6])
thresholds = [5, 7]
choices = [10, 15, 20, 25]
Expand All @@ -39,9 +36,8 @@ def test_apply_thresholds_when_too_many_choices():
assert commons.apply_thresholds(input_, thresholds, choices)


def test_concat_when_this_is_array_not_str():
def test_concat_when_this_is_array_not_str() -> None:
"""Casts ``this`` to ``str`` when it is a NumPy array other than string."""

this = numpy.array([1, 2])
that = numpy.array(["la", "o"])

Expand All @@ -50,9 +46,8 @@ def test_concat_when_this_is_array_not_str():
assert_array_equal(result, ["1la", "2o"])


def test_concat_when_that_is_array_not_str():
def test_concat_when_that_is_array_not_str() -> None:
"""Casts ``that`` to ``str`` when it is a NumPy array other than string."""

this = numpy.array(["ho", "cha"])
that = numpy.array([1, 2])

Expand All @@ -61,19 +56,17 @@ def test_concat_when_that_is_array_not_str():
assert_array_equal(result, ["ho1", "cha2"])


def test_concat_when_args_not_str_array_like():
def test_concat_when_args_not_str_array_like() -> None:
"""Raises a TypeError when args are not a string array-like object."""

this = (1, 2)
that = (3, 4)

with pytest.raises(TypeError):
commons.concat(this, that)


def test_switch_when_values_are_empty():
def test_switch_when_values_are_empty() -> None:
"""Raises an AssertionError when the values are empty."""

conditions = [1, 1, 1, 2]
value_by_condition = {}

Expand Down
6 changes: 2 additions & 4 deletions openfisca_core/commons/tests/test_rates.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,8 @@
from openfisca_core import commons


def test_average_rate_when_varying_is_zero():
def test_average_rate_when_varying_is_zero() -> None:
"""Yields infinity when the varying gross income crosses zero."""

target = numpy.array([1, 2, 3])
varying = [0, 0, 0]

Expand All @@ -15,9 +14,8 @@ def test_average_rate_when_varying_is_zero():
assert_array_equal(result, [-numpy.inf, -numpy.inf, -numpy.inf])


def test_marginal_rate_when_varying_is_zero():
def test_marginal_rate_when_varying_is_zero() -> None:
"""Yields infinity when the varying gross income crosses zero."""

target = numpy.array([1, 2, 3])
varying = numpy.array([0, 0, 0])

Expand Down
Loading
Loading