Skip to content

Commit

Permalink
Remove pylintrc and tests/pylintrc config files
Browse files Browse the repository at this point in the history
* Just use default Pylint configuration making sure that checks pass.
* Tweak code for "consider-using-f-string" and "unspecified-encoding".
* Need to disable "no-name-in-module" and "no-member" checks for ROOT.
  • Loading branch information
GraemeWatt committed Apr 4, 2024
1 parent 08b563c commit 3a0f1ea
Show file tree
Hide file tree
Showing 15 changed files with 92 additions and 1,380 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -120,4 +120,4 @@ jobs:
if: ${{ always() && !startsWith(matrix.python-version, '3.6') && !startsWith(matrix.python-version, '3.7') }}
run: |
python -m pylint hepdata_lib/*.py
python -m pylint tests/*.py --rcfile=tests/pylintrc
python -m pylint tests/*.py
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Library for getting your data into HEPData

- Documentation: https://hepdata-lib.readthedocs.io

This code works with Python 3.6, 3.7, 3.8, 3.9 or 3.10.
This code works with Python 3.6, 3.7, 3.8, 3.9, 3.10, 3.11 or 3.12.

## Installation

Expand Down
2 changes: 1 addition & 1 deletion docs/dev.rst
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ Analysing the code
::

pylint hepdata_lib/*.py
pylint tests/*.py --rcfile=tests/pylintrc
pylint tests/*.py

These commands are run by GitHub Actions (for Python 3.8 or later),
so you should first check locally that no issues are flagged.
Expand Down
20 changes: 10 additions & 10 deletions hepdata_lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def make_dict(self):
elif self.uncertainties and self.zero_uncertainties_warning:
print(
"Warning: omitting 'errors' since all uncertainties " \
"are zero for bin {} of variable '{}'.".format(i+1, self.name)
f"are zero for bin {i+1} of variable '{self.name}'."
)
print(
"Note that bins with zero content should preferably " \
Expand Down Expand Up @@ -389,7 +389,7 @@ def write_images(self, outdir):

for image_file in self.image_files:
if not os.path.isfile(image_file):
raise RuntimeError("File %s does not exist!" % image_file)
raise RuntimeError(f"File {image_file} does not exist!")

Check warning on line 392 in hepdata_lib/__init__.py

View check run for this annotation

Codecov / codecov/patch

hepdata_lib/__init__.py#L392

Added line #L392 was not covered by tests
if not os.path.exists(outdir):
os.makedirs(outdir)

Expand All @@ -408,16 +408,16 @@ def write_images(self, outdir):
if helpers.file_is_outdated(png_output_path, image_file):
helpers.convert_pdf_to_png(image_file, png_output_path)
else:
print("Full-size PNG file %s is newer than its source file. \
print(f"Full-size PNG file {png_output_path} is newer than its source file. \
Remove the thumbnail file or use create_files(remove_old=True)\
to force recreation." % png_output_path)
to force recreation.")

if helpers.file_is_outdated(thumbnail_output_path, png_output_path):
helpers.convert_png_to_thumbnail(png_output_path, thumbnail_output_path)
else:
print("Thumbnail PNG file %s is newer than its source file. \
print("Thumbnail PNG file {thumbnail_output_path} is newer than its source file. \
Remove the thumbnail file or use create_files(remove_old=True)\
to force recreation." % thumbnail_output_path)
to force recreation.")

image = {}
image["description"] = "Image file"
Expand Down Expand Up @@ -461,12 +461,12 @@ def write_yaml(self, outdir="."):
shortname = self.name.lower().replace(" ", "_")
outfile_path = os.path.join(
outdir, f'{shortname}.yaml')
with open(outfile_path, 'w') as outfile:
with open(outfile_path, 'w', encoding='utf-8') as outfile:
yaml.dump(table, outfile, default_flow_style=False)

# Add entry to central submission file
submission_path = os.path.join(outdir, 'submission.yaml')
with open(submission_path, 'a+') as submissionfile:
with open(submission_path, 'a+', encoding='utf-8') as submissionfile:
submission = {}
submission["name"] = self.name
submission["description"] = self.description
Expand Down Expand Up @@ -574,7 +574,7 @@ def read_abstract(self, filepath):
:param filepath: Path to text file containing abstract.
:type filepath: string.
"""
with open(filepath) as afile:
with open(filepath, encoding='utf-8') as afile:
raw = str(afile.read())
raw = raw.replace("\r\n", "")
raw = raw.replace("\n", "")
Expand Down Expand Up @@ -619,7 +619,7 @@ def create_files(self, outdir=".", validate=True, remove_old=False):
if self.record_ids:
submission["record_ids"] = self.record_ids

with open(os.path.join(outdir, 'submission.yaml'), 'w') as outfile:
with open(os.path.join(outdir, 'submission.yaml'), 'w', encoding='utf-8') as outfile:
yaml.dump(
submission,
outfile,
Expand Down
4 changes: 2 additions & 2 deletions hepdata_lib/c_file_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import io
from array import array
from future.utils import raise_from
from ROOT import TGraph, TGraphErrors
from ROOT import TGraph, TGraphErrors # pylint: disable=no-name-in-module
import hepdata_lib.root_utils as ru
from hepdata_lib.helpers import check_file_existence

Expand Down Expand Up @@ -34,7 +34,7 @@ def cfile(self, cfile):
"CFileReader: Input file is not a .C file (name does not end in .C)!"
)
if check_file_existence(cfile):
self._cfile = open(cfile) # pylint: disable=consider-using-with
self._cfile = open(cfile, encoding='utf-8') # pylint: disable=consider-using-with
else:
if isinstance(cfile, io.TextIOBase):
self._cfile = cfile
Expand Down
10 changes: 4 additions & 6 deletions hepdata_lib/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,10 +294,9 @@ def convert_pdf_to_png(source, target):
:param target: Output file in PNG format.
:type target: str
"""
assert os.path.exists(source), "Source file does not exist: %s" % source
assert os.path.exists(source), f"Source file does not exist: {source}"

command = "convert -flatten -density 300 -fuzz 1% -trim +repage {} {}".format(
source, target)
command = f"convert -flatten -density 300 -fuzz 1% -trim +repage {source} {target}"
command_ok = execute_command(command)
if not command_ok:
print("ImageMagick does not seem to be installed \
Expand All @@ -314,8 +313,7 @@ def convert_png_to_thumbnail(source, target):
:type target: str
"""

command = "convert -thumbnail 240x179 {} {}".format(
source, target)
command = f"convert -thumbnail 240x179 {source} {target}"
command_ok = execute_command(command)

if not command_ok:
Expand All @@ -334,7 +332,7 @@ def file_is_outdated(file_path, reference_file_path):
:type reference_file_path: str
"""
if not os.path.exists(reference_file_path):
raise RuntimeError("Reference file does not exist: %s" % reference_file_path)
raise RuntimeError(f"Reference file does not exist: {reference_file_path}")

Check warning on line 335 in hepdata_lib/helpers.py

View check run for this annotation

Codecov / codecov/patch

hepdata_lib/helpers.py#L335

Added line #L335 was not covered by tests
if not os.path.exists(file_path):
return True

Expand Down
28 changes: 13 additions & 15 deletions hepdata_lib/root_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ def tfile(self, tfile):
"RootFileReader: Input file is not a ROOT file (name does not end in .root)!"
)
if check_file_existence(tfile):
self._tfile = r.TFile(tfile)
elif isinstance(tfile, r.TFile):
self._tfile = r.TFile(tfile) # pylint: disable=no-member
elif isinstance(tfile, r.TFile): # pylint: disable=no-member
self._tfile = tfile
else:
raise ValueError(
Expand Down Expand Up @@ -157,7 +157,7 @@ def read_hist_2d(self, path_to_hist, **kwargs):
ylim = kwargs.pop('ylim', (None, None))
force_symmetric_errors = kwargs.pop('force_symmetric_errors', False)
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
raise TypeError(f'Unexpected **kwargs: {repr(kwargs)}')
assert isinstance(xlim, (tuple, list))
assert isinstance(ylim, (tuple, list))
assert len(xlim) == 2
Expand Down Expand Up @@ -193,7 +193,7 @@ def read_hist_1d(self, path_to_hist, **kwargs):
xlim = kwargs.pop('xlim', (None, None))
force_symmetric_errors = kwargs.pop('force_symmetric_errors', False)
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
raise TypeError(f'Unexpected **kwargs: {repr(kwargs)}')
assert isinstance(xlim, (tuple, list))
assert len(xlim) == 2
if xlim[0] and xlim[1]:
Expand All @@ -217,7 +217,7 @@ def read_tree(self, path_to_tree, branch_name):
"""
tree = self.tfile.Get(path_to_tree)
if not tree or not isinstance(tree, r.TTree):
if not tree or not isinstance(tree, r.TTree): # pylint: disable=no-member
raise RuntimeError(f"No TTree found for path '{path_to_tree}'.")
values = []
for event in tree:
Expand Down Expand Up @@ -297,7 +297,7 @@ def get_hist_2d_points(hist, **kwargs):
ylim = kwargs.pop('ylim', (None, None))
force_symmetric_errors = kwargs.pop('force_symmetric_errors', False)
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
raise TypeError(f'Unexpected **kwargs: {repr(kwargs)}')

Check warning on line 300 in hepdata_lib/root_utils.py

View check run for this annotation

Codecov / codecov/patch

hepdata_lib/root_utils.py#L300

Added line #L300 was not covered by tests
assert isinstance(xlim, (tuple, list))
assert isinstance(ylim, (tuple, list))
assert len(xlim) == 2
Expand All @@ -317,7 +317,7 @@ def get_hist_2d_points(hist, **kwargs):
ixmax = hist.GetXaxis().FindBin(xlim[1]) if xlim[1] is not None else hist.GetNbinsX() + 1
iymin = hist.GetYaxis().FindBin(ylim[0]) if ylim[0] is not None else 1
iymax = hist.GetYaxis().FindBin(ylim[1]) if ylim[1] is not None else hist.GetNbinsY() + 1
symmetric = hist.GetBinErrorOption() == r.TH1.kNormal
symmetric = hist.GetBinErrorOption() == r.TH1.kNormal # pylint: disable=no-member
if force_symmetric_errors:
symmetric = True
for x_bin in range(ixmin, ixmax):
Expand Down Expand Up @@ -377,7 +377,7 @@ def get_hist_1d_points(hist, **kwargs):
xlim = kwargs.pop('xlim', (None, None))
force_symmetric_errors = kwargs.pop('force_symmetric_errors', False)
if kwargs:
raise TypeError('Unexpected **kwargs: %r' % kwargs)
raise TypeError(f'Unexpected **kwargs: {repr(kwargs)}')

Check warning on line 380 in hepdata_lib/root_utils.py

View check run for this annotation

Codecov / codecov/patch

hepdata_lib/root_utils.py#L380

Added line #L380 was not covered by tests
assert isinstance(xlim, (tuple, list))
assert len(xlim) == 2
if xlim[0] and xlim[1]:
Expand All @@ -388,7 +388,7 @@ def get_hist_1d_points(hist, **kwargs):
for key in ["x", "y", "x_edges", "x_labels", "dy"]:
points[key] = []

symmetric = hist.GetBinErrorOption() == r.TH1.kNormal
symmetric = hist.GetBinErrorOption() == r.TH1.kNormal # pylint: disable=no-member
if force_symmetric_errors:
symmetric = True
ixmin = hist.GetXaxis().FindBin(xlim[0]) if xlim[0] is not None else 1
Expand Down Expand Up @@ -430,10 +430,8 @@ def get_graph_points(graph):
"""

# Check input
if not isinstance(graph, (r.TGraph, r.TGraphErrors, r.TGraphAsymmErrors)):
raise TypeError(
"Expected to input to be TGraph or similar, instead got '{0}'".
format(type(graph)))
if not isinstance(graph, (r.TGraph, r.TGraphErrors, r.TGraphAsymmErrors)): # pylint: disable=no-member
raise TypeError(f"Expected to input to be TGraph or similar, instead got '{type(graph)}'")

Check warning on line 434 in hepdata_lib/root_utils.py

View check run for this annotation

Codecov / codecov/patch

hepdata_lib/root_utils.py#L434

Added line #L434 was not covered by tests

# Extract points
points = defaultdict(list)
Expand All @@ -444,10 +442,10 @@ def get_graph_points(graph):
graph.GetPoint(i, x_val, y_val)
points["x"].append(float(x_val.value))
points["y"].append(float(y_val.value))
if isinstance(graph, r.TGraphErrors):
if isinstance(graph, r.TGraphErrors): # pylint: disable=no-member
points["dx"].append(graph.GetErrorX(i))
points["dy"].append(graph.GetErrorY(i))
elif isinstance(graph, r.TGraphAsymmErrors):
elif isinstance(graph, r.TGraphAsymmErrors): # pylint: disable=no-member
points["dx"].append((-graph.GetErrorXlow(i),
graph.GetErrorXhigh(i)))
points["dy"].append((-graph.GetErrorYlow(i),
Expand Down
Loading

0 comments on commit 3a0f1ea

Please sign in to comment.