Skip to content

Commit

Permalink
Switch to ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
inducer committed Jun 27, 2024
1 parent 5292165 commit a050524
Show file tree
Hide file tree
Showing 29 changed files with 206 additions and 150 deletions.
11 changes: 4 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,13 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
-
uses: actions/setup-python@v5
with:
# matches compat target in setup.py
python-version: '3.8'
submodules: true
- uses: actions/setup-python@v5
- name: "Main Script"
run: |
curl -L -O https://tiker.net/ci-support-v0
. ci-support-v0
install_and_run_flake8 "$(get_proj_name)" examples/*.py test/*.py
pip install ruff
ruff check
pylint:
name: Pylint
Expand Down
9 changes: 4 additions & 5 deletions .gitlab-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -167,12 +167,11 @@ Python 3 POCL (+GL and special functions):

Flake8:
script: |
curl -L -O https://tiker.net/ci-support-v0
. ci-support-v0
build_py_project_in_venv
install_and_run_flake8 "$(get_proj_name)" examples/*.py test/*.py
pip install ruff
ruff check
tags:
- python3
- docker-runner
except:
- tags

Expand Down Expand Up @@ -241,7 +240,7 @@ Downstream:
- DOWNSTREAM_PROJECT: [loopy, boxtree, meshmode]
tags:
- large-node
- "docker-runner"
- docker-runner
script: |
curl -L -O https://tiker.net/ci-support-v0
. ci-support-v0
Expand Down
6 changes: 3 additions & 3 deletions contrib/cldis.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
import tempfile


def main(ctx, tmp_dir, cl_str, output=None, build_options=[]):
def main(ctx, tmp_dir, cl_str, output=None, build_options=()):
device = ctx.devices[0]
platform = device.platform
if platform.name == "NVIDIA CUDA":
Expand Down Expand Up @@ -86,6 +86,6 @@ def main(ctx, tmp_dir, cl_str, output=None, build_options=[]):
cl_file = sys.argv[1]
with open(cl_file, "r") as f:
cl_str = f.read()
output = sys.argv[2] if len(sys.argv) >=3 else None
build_options = sys.argv[3:] if len(sys.argv) >=4 else []
output = sys.argv[2] if len(sys.argv) >= 3 else None
build_options = sys.argv[3:] if len(sys.argv) >= 4 else []
main(ctx, tmp_dir, cl_str, output, build_options)
13 changes: 9 additions & 4 deletions contrib/fortran-to-opencl/translate.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@
from sys import intern
from warnings import warn

import cgen
import numpy as np

import cgen
import pymbolic.primitives as p
import pytools.lex
from pymbolic.mapper import CombineMapper
Expand Down Expand Up @@ -233,8 +234,12 @@ def parse_prefix(self, pstate, min_precedence=0):

def parse_postfix(self, pstate, min_precedence, left_exp):
from pymbolic.parser import (
_PREC_CALL, _PREC_COMPARISON, _PREC_LOGICAL_AND, _PREC_LOGICAL_OR,
_openpar)
_PREC_CALL,
_PREC_COMPARISON,
_PREC_LOGICAL_AND,
_PREC_LOGICAL_OR,
_openpar,
)
from pymbolic.primitives import Comparison, LogicalAnd, LogicalOr

next_tag = pstate.next_tag()
Expand Down Expand Up @@ -941,7 +946,7 @@ def gen_shape(start_end):

if shape is not None:
dim_stmt = cgen.Statement(
'dimension \"fortran\" {}[{}]'.format(
'dimension "fortran" {}[{}]'.format(
scope.translate_var_name(name),
", ".join(gen_shape(s) for s in shape)
))
Expand Down
14 changes: 12 additions & 2 deletions examples/demo_meta_codepy.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import numpy as np
import numpy.linalg as la

from cgen import (
POD, Assign, Block, Const, FunctionBody, FunctionDeclaration, Initializer,
Module, Pointer, Value)
POD,
Assign,
Block,
Const,
FunctionBody,
FunctionDeclaration,
Initializer,
Module,
Pointer,
Value,
)
from cgen.opencl import CLGlobal, CLKernel, CLRequiredWorkGroupSize

import pyopencl as cl
Expand Down
6 changes: 4 additions & 2 deletions examples/svm.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@

import pyopencl as cl
from pyopencl.characterize import (
has_coarse_grain_buffer_svm, has_fine_grain_buffer_svm,
has_fine_grain_system_svm)
has_coarse_grain_buffer_svm,
has_fine_grain_buffer_svm,
has_fine_grain_system_svm,
)


ctx = cl.create_some_context()
Expand Down
3 changes: 1 addition & 2 deletions examples/transpose.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,7 @@ def benchmark_transpose():
a_t_buf.release()

try:
from matplotlib.pyplot import (
clf, grid, legend, plot, savefig, xlabel, ylabel)
from matplotlib.pyplot import clf, grid, legend, plot, savefig, xlabel, ylabel
except ModuleNotFoundError:
pass
else:
Expand Down
24 changes: 12 additions & 12 deletions pyopencl/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,11 +443,11 @@ def __getattr__(self, attr):
knl = Kernel(self, attr)
# Nvidia does not raise errors even for invalid names,
# but this will give an error if the kernel is invalid.
knl.num_args
knl.num_args # noqa: B018
knl._source = getattr(self, "_source", None)

if self._build_duration_info is not None:
build_descr, was_cached, duration = self._build_duration_info
build_descr, _was_cached, duration = self._build_duration_info
if duration > 0.2:
logger.info("build program: kernel '%s' was part of a "
"lengthy %s (%.2f s)" % (attr, build_descr, duration))
Expand All @@ -456,9 +456,9 @@ def __getattr__(self, attr):
self._build_duration_info = None

return knl
except LogicError:
except LogicError as err:
raise AttributeError("'%s' was not found as a program "
"info attribute or as a kernel name" % attr)
"info attribute or as a kernel name" % attr) from err

# {{{ build

Expand Down Expand Up @@ -780,9 +780,9 @@ def __getattr__(self, name):

try:
inf_attr = getattr(info_cls, name.upper())
except AttributeError:
except AttributeError as err:
raise AttributeError("%s has no attribute '%s'"
% (type(self), name))
% (type(self), name)) from err
else:
return self.event.get_profiling_info(inf_attr)

Expand Down Expand Up @@ -1030,9 +1030,9 @@ def __init__(self, event):
def __getattr__(self, name):
try:
inf_attr = getattr(_cl.image_info, name.upper())
except AttributeError:
except AttributeError as err:
raise AttributeError("%s has no attribute '%s'"
% (type(self), name))
% (type(self), name)) from err
else:
return self.event.get_image_info(inf_attr)

Expand All @@ -1055,7 +1055,7 @@ def image_shape(self):
def error_str(self):
val = self.what
try:
val.routine
val.routine # noqa: B018
except AttributeError:
return str(val)
else:
Expand Down Expand Up @@ -2097,7 +2097,7 @@ def enqueue_fill(queue: CommandQueue,
np.dtype(np.uint8): channel_type.UNSIGNED_INT8,
}
try:
np.float16
np.float16 # noqa: B018
except Exception:
pass
else:
Expand Down Expand Up @@ -2272,12 +2272,12 @@ def svm_empty(ctx, flags, shape, dtype, order="C", alignment=None, queue=None):
s = 1
for dim in shape:
s *= dim
except TypeError:
except TypeError as err:
admissible_types = (int, np.integer)

if not isinstance(shape, admissible_types):
raise TypeError("shape must either be iterable or "
"castable to an integer")
"castable to an integer") from err
s = shape
shape = (shape,)

Expand Down
4 changes: 2 additions & 2 deletions pyopencl/_mymako.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
try:
import mako.template # noqa: F401
except ImportError:
except ImportError as err:
raise ImportError(
"Some of PyOpenCL's facilities require the Mako templating engine.\n"
"You or a piece of software you have used has tried to call such a\n"
Expand All @@ -9,6 +9,6 @@
"- easy_install Mako\n"
"- pip install Mako\n"
"- aptitude install python-mako\n"
"\nor whatever else is appropriate for your system.")
"\nor whatever else is appropriate for your system.") from err

from mako import * # noqa: F401, F403
3 changes: 2 additions & 1 deletion pyopencl/algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

import numpy as np
from mako.template import Template

from pytools import memoize, memoize_method

import pyopencl as cl
Expand Down Expand Up @@ -1226,7 +1227,7 @@ def __call__(self, queue, n_objects, *args, **kwargs):
queue, (n_objects + 1,), index_dtype, allocator=allocator)
info_record.compressed_indices[0] = 0

compress_events[name] = compress_kernel( \
compress_events[name] = compress_kernel(
# pylint: disable=possibly-used-before-assignment
info_record.starts,
compressed_counts,
Expand Down
19 changes: 11 additions & 8 deletions pyopencl/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,12 @@
from pyopencl import cltypes
from pyopencl.characterize import has_double_support
from pyopencl.compyte.array import (
ArrayFlags as _ArrayFlags, as_strided as _as_strided,
c_contiguous_strides as _c_contiguous_strides, equal_strides as _equal_strides,
f_contiguous_strides as _f_contiguous_strides)
ArrayFlags as _ArrayFlags,
as_strided as _as_strided,
c_contiguous_strides as _c_contiguous_strides,
equal_strides as _equal_strides,
f_contiguous_strides as _f_contiguous_strides,
)


SCALAR_CLASSES = (Number, np.bool_, bool)
Expand Down Expand Up @@ -608,11 +611,11 @@ def __init__(

try:
shape = tuple(shape) # type: ignore[arg-type]
except TypeError:
except TypeError as err:
if not isinstance(shape, (int, np.integer)):
raise TypeError(
"shape must either be iterable or castable to an integer: "
f"got a '{type(shape).__name__}'")
f"got a '{type(shape).__name__}'") from err

shape = (shape,)

Expand Down Expand Up @@ -654,7 +657,7 @@ def __init__(
# }}}

assert dtype != object, \
"object arrays on the compute device are not allowed"
"object arrays on the compute device are not allowed" # noqa: E721
assert isinstance(shape, tuple)
assert isinstance(strides, tuple)

Expand Down Expand Up @@ -922,7 +925,7 @@ def get(self, queue=None, ary=None, async_=None, **kwargs):
"device-to-host transfers",
DeprecationWarning, stacklevel=2)

ary, event1 = self._get(queue=queue, ary=ary, async_=async_, **kwargs)
ary, _event1 = self._get(queue=queue, ary=ary, async_=async_, **kwargs)

return ary

Expand Down Expand Up @@ -2370,7 +2373,7 @@ def to_device(queue, ary, allocator=None, async_=None,

# }}}

if ary.dtype == object:
if ary.dtype == object: # noqa: E721
raise RuntimeError("to_device does not work on object arrays.")

if array_queue is _same_as_transfer:
Expand Down
1 change: 1 addition & 0 deletions pyopencl/bitonic_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from operator import mul

from mako.template import Template

from pytools import memoize_method

import pyopencl as cl
Expand Down
12 changes: 6 additions & 6 deletions pyopencl/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def get_cache_key(device, options_bytes, src):


def retrieve_from_cache(cache_dir, cache_key):
class _InvalidInfoFile(RuntimeError):
class _InvalidInfoFileError(RuntimeError):
pass

from os.path import isdir, join
Expand All @@ -290,18 +290,18 @@ class _InvalidInfoFile(RuntimeError):

try:
info_file = open(info_path, "rb")
except OSError:
raise _InvalidInfoFile()
except OSError as err:
raise _InvalidInfoFileError() from err

try:
try:
info = load(info_file)
except EOFError:
raise _InvalidInfoFile()
except EOFError as err:
raise _InvalidInfoFileError() from err
finally:
info_file.close()

except _InvalidInfoFile:
except _InvalidInfoFileError:
mod_cache_dir_m.reset()
from warnings import warn
warn(
Expand Down
9 changes: 5 additions & 4 deletions pyopencl/capture_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@


import numpy as np

from pytools.py_codegen import Indentation, PythonCodeGenerator

import pyopencl as cl
Expand All @@ -30,8 +31,8 @@
def capture_kernel_call(kernel, output_file, queue, g_size, l_size, *args, **kwargs):
try:
source = kernel._source
except AttributeError:
raise RuntimeError("cannot capture call, kernel source not available")
except AttributeError as err:
raise RuntimeError("cannot capture call, kernel source not available") from err

if source is None:
raise RuntimeError("cannot capture call, kernel source not available")
Expand Down Expand Up @@ -91,9 +92,9 @@ def capture_kernel_call(kernel, output_file, queue, g_size, l_size, *args, **kwa
else:
try:
arg_buf = memoryview(arg)
except Exception:
except Exception as err:
raise RuntimeError("cannot capture: "
"unsupported arg nr %d (0-based)" % i)
"unsupported arg nr %d (0-based)" % i) from err

arg_data.append(("arg%d_data" % i, arg_buf))
kernel_args.append("decompress(b64decode(arg%d_data))" % i)
Expand Down
1 change: 1 addition & 0 deletions pyopencl/clrandom.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
# }}}

import numpy as np

from pytools import memoize_method

import pyopencl as cl
Expand Down
Loading

0 comments on commit a050524

Please sign in to comment.