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

Unify syntax, add style checks, remove obsolete Python 2 leftovers #1047

Open
wants to merge 128 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
128 commits
Select commit Hold shift + click to select a range
9ea8f40
Sort deps alphabetically
Sep 27, 2021
69d0f04
Add pylint
Sep 27, 2021
b44656b
Add pylint to setup.cfg
Sep 27, 2021
7382fdb
Add pylint to Makefile
Sep 27, 2021
9e75385
Add pyupgrade to auto correct outdated syntax
Sep 27, 2021
5360c13
Fix outdated syntax
Sep 27, 2021
21fd36a
Remove unneeded ifs
Sep 27, 2021
ec2af12
Fix imports
Sep 27, 2021
d44c0a1
Ignore reimports check
Sep 27, 2021
67c6bbb
Fix unused self
Sep 27, 2021
50825a9
Ignore private access to avoid breaking-changes
Sep 27, 2021
ab57014
Add missing raise from
Sep 27, 2021
0808730
Fix isinstances
Sep 27, 2021
33efe59
Ignore required self because OpenFisca
Sep 27, 2021
fdca9ed
Ignore todos for now
Sep 27, 2021
eb8bef3
Fix parameter rename
Sep 27, 2021
89e5d2c
Fix wrong imports
Sep 27, 2021
6f28227
Use items() to iterate
Sep 27, 2021
b845734
Ignore index lookup check (pylint bug)
Sep 27, 2021
9e6bdf9
Fix inconsistent expressions
Sep 27, 2021
bfe3747
Ignore wildcard imports
Sep 27, 2021
55318de
Fix missing imports
Sep 27, 2021
34067a1
Fix broad exception catch
Sep 27, 2021
48ce1ca
Fix failing test
Sep 27, 2021
80a83ca
Ignore abstract class error
Sep 27, 2021
e86bc12
Fix useless alias
Sep 27, 2021
018ff46
Fix cryptic comment
Sep 27, 2021
a1c808e
Fix len sequence comparison
Sep 27, 2021
8b5d73f
Move pylint config to setup.cfg
Sep 27, 2021
cdd1c5e
Ignore unused arguments
Sep 27, 2021
660937f
Ignore similar code check
Sep 28, 2021
771a26c
Remove parens after if
Sep 28, 2021
d52a554
Remove parens after assert
Sep 28, 2021
759010b
Use isinstance for type casts
Sep 28, 2021
4594476
Fix misplaced comparisons
Sep 28, 2021
1d2d503
Ignore attrs defined outside__init__
Sep 28, 2021
50b7d87
Fix useless pass
Sep 28, 2021
618ab64
Ignore pointless statements (false positive)
Sep 28, 2021
3aafdda
Ignore redefinitions (otherwise breaking-change)
Sep 28, 2021
314d790
Use lazy interpolation for logs
Sep 28, 2021
71b99c0
Ignore uncalled __init__
Sep 28, 2021
e6646da
Fix cls assignment
Sep 28, 2021
68f3ea7
Fix open without encoding
Sep 28, 2021
075e7fa
Ignore no value for %
Sep 28, 2021
45c8a45
Fix unused variables
Sep 28, 2021
b8ae82e
Fix deprecated warn use
Sep 28, 2021
a408f4d
Fix use of deprecated imp
Sep 28, 2021
a41b8b9
Ignore too many returns (for now)
Sep 28, 2021
969b7fb
Fix parens in return
Sep 28, 2021
47fa396
Remove broken migration
Sep 28, 2021
5b49259
Fix undef loop variable
Sep 28, 2021
8eec529
Ignore override errors (for now)
Sep 28, 2021
65d8da2
Fix context manager use
Sep 28, 2021
8f3c16a
Fix globals use
Sep 28, 2021
a2bfd9a
Fix misplaced docstrings
Sep 28, 2021
fc925b4
Remove broken script
Sep 28, 2021
60f717b
Remove useless constant condition test
Sep 28, 2021
89c220e
Do not use exec
Sep 28, 2021
751e0e5
Document exceptions
Sep 28, 2021
1d3ce1f
Fix file split
Sep 28, 2021
29eabf8
Bump minor to 35.6.0
Sep 28, 2021
0fe1f1e
Fix circleci
Sep 28, 2021
3549667
Set shell for circleci
Sep 28, 2021
b4c1dd3
Merge branch 'master' into add-pylint
bonjourmauko Sep 10, 2022
d35ef00
Remove unused package import
bonjourmauko Sep 10, 2022
1c56180
Automate import sorting
bonjourmauko Sep 10, 2022
db3e85b
Expire deprecations
bonjourmauko Sep 10, 2022
7ddf437
Remove unused imports
bonjourmauko Sep 10, 2022
7b69afa
Fix enum circular import
bonjourmauko Sep 10, 2022
95241f2
Fix deprecated imports
bonjourmauko Sep 10, 2022
7bae924
Fix param circular import:
bonjourmauko Sep 10, 2022
2f4d695
Fix several circular imports
bonjourmauko Sep 10, 2022
1cf10f0
Remove unused var declaration
bonjourmauko Sep 10, 2022
0c7dfe4
Fix serveral imports
bonjourmauko Sep 11, 2022
4a5dc74
Unify equals use
bonjourmauko Sep 11, 2022
34d1510
Fix private access in tracer
bonjourmauko Sep 11, 2022
e98da1b
Unpin dev dependencies
bonjourmauko Sep 11, 2022
a35fafd
Update print chack skip code
bonjourmauko Sep 11, 2022
8e28dfc
Fix faux abstract class def
bonjourmauko Sep 11, 2022
2dd6f31
Fix pylint config
bonjourmauko Sep 11, 2022
cd1a605
Remove abstract classes tests
bonjourmauko Sep 12, 2022
a354f4e
Fix empty clone
bonjourmauko Sep 12, 2022
e8c52f6
Remove expired Bracket
bonjourmauko Sep 12, 2022
ab9dd29
Fix non-semantic imports
bonjourmauko Sep 12, 2022
7c74ab3
Fix ill-conceived asserts
bonjourmauko Sep 12, 2022
c3dd0b4
Fix f-strings in variables
bonjourmauko Sep 12, 2022
87e5c72
Fix f-strings in holders
bonjourmauko Sep 12, 2022
b9ec41f
Fix f-strings in parameters
bonjourmauko Sep 12, 2022
5137e58
Fix f-strings in reforms
bonjourmauko Sep 12, 2022
0e3544e
Fix f-strings in simulations
bonjourmauko Sep 12, 2022
d5d23e6
Fix f-strings in tools
bonjourmauko Sep 12, 2022
e4b3cf0
Fix f-strings in web-api
bonjourmauko Sep 12, 2022
e0e9cbf
Fix missing timeout in request
bonjourmauko Sep 12, 2022
b174319
Fix spurious middle import
bonjourmauko Sep 12, 2022
a529ac8
Make Holder.to_array public
bonjourmauko Sep 12, 2022
20ed12c
Rename Holder._set to .put
bonjourmauko Sep 12, 2022
385771d
Remove doc from EnumArray
bonjourmauko Sep 12, 2022
cb4f88f
Make parameters.compose_name public
bonjourmauko Sep 12, 2022
500bf74
Make parameters.validate_parameter public
bonjourmauko Sep 12, 2022
f8e9332
Remove faux properties
bonjourmauko Sep 12, 2022
4c2e091
Skip enum inheritance check
bonjourmauko Sep 12, 2022
aedcd4d
Fix unnecesary index lookup
bonjourmauko Sep 12, 2022
a53dbe8
Fix pointless statement:
bonjourmauko Sep 12, 2022
7f38ca7
Fix dpath leftover
bonjourmauko Sep 12, 2022
46da0a2
Fix falsey comparison
bonjourmauko Sep 12, 2022
dcc596b
Remove superfluous call to __setattr__
bonjourmauko Sep 12, 2022
e97b923
Skip nptying related errors
bonjourmauko Sep 12, 2022
ba524c6
Skip improper inheritance check
bonjourmauko Sep 13, 2022
8a1b621
Fix inheritance overwrite in test runner
bonjourmauko Sep 13, 2022
e473e95
Remove aliases
bonjourmauko Sep 13, 2022
ce2f8dd
Use pass and ... consistently
bonjourmauko Sep 13, 2022
b0ace29
Remove useless self
bonjourmauko Sep 13, 2022
dbad0ff
Explain empty overriden method
bonjourmauko Sep 13, 2022
87b89c6
Expire values history deprecation
bonjourmauko Sep 13, 2022
7a74e7c
Fix error message
bonjourmauko Sep 13, 2022
a69481a
Fix error message
bonjourmauko Sep 13, 2022
d4b0c51
Replace My with Fixture
bonjourmauko Sep 13, 2022
1d1ae7c
Normalise file use in context manager
bonjourmauko Sep 13, 2022
04e544f
Fix error message
bonjourmauko Sep 13, 2022
f785f78
Fix useless assignment
bonjourmauko Sep 13, 2022
1020c25
Fix tracer period type hint
bonjourmauko Sep 13, 2022
bf6cbb9
Fix commons type hints
bonjourmauko Sep 13, 2022
5c1c382
Bump version
bonjourmauko Sep 13, 2022
4b0f531
Honestify dependecies' versions
bonjourmauko Sep 14, 2022
922fd75
Mark as release candidate
bonjourmauko Sep 14, 2022
2a5d852
Remove unused import
bonjourmauko Sep 14, 2022
970798d
Normalise quotes
bonjourmauko Sep 14, 2022
bf173bc
Update CHANGELOG
bonjourmauko Sep 23, 2022
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
9 changes: 5 additions & 4 deletions .github/get-numpy-version.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,14 @@

from __future__ import annotations

import os
import sys
import typing
from packaging import version
from typing import NoReturn, Union

import os
import sys

import numpy
from packaging import version

if typing.TYPE_CHECKING:
from packaging.version import LegacyVersion, Version
Expand All @@ -26,7 +27,7 @@ def prev() -> NoReturn:
sys.exit(os.EX_DATAERR)

minor -= 1
print(f"{major}.{minor}.0") # noqa: T001
print(f"{major}.{minor}.0") # noqa: T201
sys.exit(os.EX_OK)


Expand Down
12 changes: 6 additions & 6 deletions .github/get_pypi_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ def get_info(package_name: str = "") -> dict:
if package_name == "":
raise ValueError("Package name not provided.")
url = f"https://pypi.org/pypi/{package_name}/json"
print(f"Calling {url}") # noqa: T001
resp = requests.get(url)
print(f"Calling {url}") # noqa: T201
resp = requests.get(url, timeout = 30)
if resp.status_code != 200:
raise Exception(f"ERROR calling PyPI ({url}) : {resp}")
resp = resp.json()
Expand All @@ -44,15 +44,15 @@ def replace_in_file(filepath: str, info: dict):
::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, "wt", encoding = "utf-8") as fout:
fout.write(meta)
print(f"File {filepath} has been updated with info from PyPi.") # noqa: T001
print(f"File {filepath} has been updated with info from PyPi.") # noqa: T201


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

# 36.0.0.rc1 [#1047](https://github.com/openfisca/openfisca-core/pull/1047)

#### Technical changes

- Document/honestify:
- Styles as enforced and skipped in `setup.cfg`
- Actual dependecy versions whith whom OpenFisca runs in py37-39 (note that
this library does not run with py36, py310, numpy v1.17, etc., which is not
product of any particular change introduced by this changeset)
- Make style checks stricter and clearer to help developers contribute:
- Early returns are prefered for readability and performance
- Before:
```py
if 1 > n:
var = something
else:
var = something_else

return var
```
- After:
```py
if 1 > n:
return something

return something_elses
```
- Normalise the use of:
- Quotes is normalised to double-quotes
- `@staticmethod` when `self` is unused
- `except from` for better exception context
- `isinstance()` as per the best practice
- f-strings as per good practice
- Favour:
- `...` as a placeholder and `pass` for loops
- Relative to absolute imports to avoid circularity
- Import sorting as described in the [STYLEGUIDE](STYLEGUIDE.md)
- Avoid:
- Catch-all exceptions in favour of more specific ones
- Import aliases (so `np` becomes `numpy`)
- Remove:
- Code using `exec` because dangerous and hard to maintain
- Extract:
- Common imports to `commons.imports`
- Most of these can be:
- Corrected automatically running `make format-style`
- Fixed by hand with the output of `make test` and `make style-check`

#### New features

- Rename and makes the following public (note this are not considered as
breking changes because methods were private, so renaming them to make
them public counts as actually adding a new publicly exposed method, while
removing a private method doesn't count as a breaking change):
- `Holder._to_array` to `Holder.to_array`
- `Holder._set` to `Holder.put`
- `Holder._memory_storage` to `Holder.memory_storage`
- `parameters._compose_name` to `parameters.compose_name`
- `parameters._validate_parameter` to `parameters.validate_parameter`
- `ParameterNodeAtInstant._name` to `ParameterNodeAtInstant.name`
- `ParameterNodeAtInstant._instant_str` to `ParameterNodeAtInstant.instant_str`
- `ParameterNodeAtInstant._children` to `ParameterNodeAtInstant.children`
- `Population._holders` to `Population.holders`
- `simulations._get_person_count` to `simulations.get_person_count`
- `Simulation._check_for_cycle` to `Simulation.check_for_cycle`
- `Simulation._check_period_consistency` to `Simulation.check_period_consistency`
- `FlatTracer._enter_calculation` to `FlatTracer.enter_calculation`
- `FlatTracer._exit_calculation` to `FlatTracer.exit_calculation`
- `FlatTracer._start_time` to `FlatTracer.start_time`
- `FlatTracer._end_time` to `FlatTracer.end_time`
- `PerformanceLog._json` to `PerformanceLog.json`
- Add:
- `periods.year_start`
- `periods.year_end`
- Extend:
- `test_runner.YamlItem.repr_failure` with a third argument `style` as per
the definition of the class it inherits from.

#### Breaking changes

- Expire deprecation of:
- The `Dummy` class, now provided by `commons`
- `formula_helpers`, now provided by `commons`
- `memory_config`, now provided by `experimental`
- `rates`, now provided by `commons`
- `Scale`, now provided by `ParameterScale`
- `Bracket`, now provided by `ParameterScaleBracket`
- `ValuesHistory`, now provided by `ParameterScale`
- `ParameterNotFound`, now provided by `ParameterNotFoundError`
- `VariableNameConflict`, now provided by `VariableNameConflictError`
- `VariableNotFound`, now provided by `VariableNotFoundError`
- `simulation_builder`, now provided by `simulations`
- `openfisca-run-test`, now provided by `openfisca test`
- `TaxBenefitSystem.new_scenario`, now provided by `SimulationBuilder`
- `AbstractRateTaxScale`, now provided by `RateTaxScaleLike`
- `AbstractTaxScale`, now provided by `TaxScaleLike`
- _In fine_, All errors that were not but are not under `errors`
- Delete (no replacement):
- `scripts.measure_performance`
- `scripts.migrations.v16_2_to_v17`
- Normalise the use of:
- `file_path` for file context-managers (implies argument name rename)

#### Publising instructions

Because this library has a circular depedency with `openfisca-country-template`
and `openfisca-extension-template`, publish of this version requires:
1. Publishing of one or many release candidates
2. Publishing next major or `openfisca-country-template`
3. Publishing next major or `openfisca-extension-template`
4. Publishing next major of this library
5. Publishing due diligence or unexpected outcome fixes as a release candidates

### 35.9.0 [#1150](https://github.com/openfisca/openfisca-core/pull/1150)

#### New Features
Expand Down Expand Up @@ -383,7 +496,7 @@ Here is a subset of the deprecations that you might find in your model with some
* Before `np.select([], [])` result was `0` (for a `default` argument value set to `0`).
* Now, we have to check for empty conditions and, return `0` or the defined default argument value when we want to keep the same behavior.
* Before, integer conditions where transformed to booleans.
* For example, `np.select([0, 1, 0], ['a', 'b', 'c'])` result was `array('b', dtype='<U21')`. Now, we have to update such code to: `np.select(np.array([0, 1, 0]).astype(bool), ['a', 'b', 'c'])`.
* For example, `np.select([0, 1, 0], ['a', 'b', 'c'])` result was `array('b', dtype = '<U21')`. Now, we have to update such code to: `np.select(np.array([0, 1, 0]).astype(bool), ['a', 'b', 'c'])`.
* `np.linspace parameter num must be an integer.`
* No surprise here, update the `num` parameter in [np.linspace](https://numpy.org/doc/1.18/reference/generated/numpy.linspace.html) in order to get an integer.
* `Array order only accepts ‘C’, ‘F’, ‘A’, and ‘K’.`
Expand Down Expand Up @@ -2664,7 +2777,7 @@ For more information, check the [documentation](https://openfisca.org/doc/coding

def reform_modify_parameters(parameters):
file_path = os.path.join(dir_path, 'plf2016.yaml')
reform_parameters_subtree = load_parameter_file(name = 'plf2016', file_path=file_path)
reform_parameters_subtree = load_parameter_file(name = 'plf2016', file_path = file_path)
parameters.add_child('plf2016', reform_parameters_subtree)
return parameters

Expand Down Expand Up @@ -3262,14 +3375,14 @@ Unlike simple formulas, a `DatedVariable` have several functions. We thus need t

## 2.2.0

* Implement simulation.calculate `print_trace=True` argument. Options: `max_depth` and `show_default_values`
* Implement simulation.calculate `print_trace = True` argument. Options: `max_depth` and `show_default_values`

Examples:
```python
simulation = scenario.new_simulation(trace=True)
simulation.calculate('irpp', 2014, print_trace=True)
simulation.calculate('irpp', 2014, print_trace=True, max_depth=-1)
simulation.calculate('irpp', 2014, print_trace=True, max_depth=-1, show_default_values=False)
simulation = scenario.new_simulation(trace = True)
simulation.calculate('irpp', 2014, print_trace = True)
simulation.calculate('irpp', 2014, print_trace = True, max_depth = -1)
simulation.calculate('irpp', 2014, print_trace = True, max_depth = -1, show_default_values = False)
```

## 2.1.0 – [diff](https://github.com/openfisca/openfisca-core/compare/2.0.3...2.0.4)
Expand Down
4 changes: 1 addition & 3 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class Cache:
"""

def __init__(self, type: str) -> None:
pass
...

```

Expand Down Expand Up @@ -197,6 +197,4 @@ def get(self, key: str) -> Any:

"""

pass

```
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ git clone https://github.com/openfisca/openfisca-core.git
cd openfisca-core
python3 -m venv .venv
source .venv/bin/activate
pip install -U pip
pip install --editable .[dev] --use-deprecated=legacy-resolver
pip install --user pip
pip install --editable ".[dev]"
```

### Installing `openfisca-core` with `conda`
Expand Down
15 changes: 1 addition & 14 deletions openfisca_core/commons/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,6 @@
* :func:`.stringify_array`
* :func:`.switch`

Deprecated:
* :class:`.Dummy`

Note:
The ``deprecated`` imports are transitional, in order to ensure non-breaking
changes, and could be removed from the codebase in the next
major release.

Note:
How imports are being used today::

Expand Down Expand Up @@ -53,15 +45,10 @@
# Official Public API

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

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

# Deprecated

from .dummy import Dummy # noqa: F401

__all__ = ["Dummy", *__all__]
23 changes: 0 additions & 23 deletions openfisca_core/commons/dummy.py

This file was deleted.

4 changes: 2 additions & 2 deletions openfisca_core/commons/formulas.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,12 @@ def concat(this: ArrayLike[str], that: ArrayLike[str]) -> ArrayType[str]:
if isinstance(this, numpy.ndarray) and \
not numpy.issubdtype(this.dtype, numpy.str_):

this = this.astype('str')
this = this.astype("str")

if isinstance(that, numpy.ndarray) and \
not numpy.issubdtype(that.dtype, numpy.str_):

that = that.astype('str')
that = that.astype("str")

return numpy.char.add(this, that)

Expand Down
48 changes: 48 additions & 0 deletions openfisca_core/commons/imports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from types import ModuleType
from typing import Tuple

import importlib
import os
import traceback
import warnings

import yaml

from openfisca_core.warnings import LibYAMLWarning


def import_country_package(country_package_name: str) -> ModuleType:
"""Import a country package."""

try:
return importlib.import_module(country_package_name)

except ImportError as error:
message = os.linesep.join([
traceback.format_exc(),
f"Could not import module `{country_package_name}`. Are you sure",
"it is installed in your environment? If so, look at the stack",
"trace above to determine the origin of this error. See more at",
"<https://github.com/openfisca/country-template#installing>.",
os.linesep,
])

raise ImportError(message) from error


def import_yaml() -> Tuple[ModuleType, yaml.cyaml.CLoader]:
"""Import the yaml library."""

try:
return yaml, yaml.__getattribute__("CLoader")

except AttributeError:
message = [
"libyaml is not installed in your environment.",
"This can make your test suite slower to run. Once you have",
"installed libyaml, run 'pip uninstall pyyaml && pip install",
"pyyaml --no-cache-dir' so that it is used in your Python",
"environment.",
]
warnings.warn(" ".join(message), LibYAMLWarning)
return yaml, yaml.__getattribute__("SafeLoader")
9 changes: 5 additions & 4 deletions openfisca_core/commons/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,18 @@ def empty_clone(original: T) -> T:
"""

Dummy: object
new: T
dummy: T

Dummy = type(
"Dummy",
(original.__class__,),
{"__init__": lambda self: None},
)

new = Dummy()
new.__class__ = original.__class__
return new
dummy = Dummy()
dummy.__class__ = original.__class__

return dummy


def stringify_array(array: ArrayType) -> str:
Expand Down
Loading