Skip to content

Commit d4ff7ae

Browse files
authored
Fix some typos and lints (#6300)
* Use `a not in b` instead of `not a in b` * Remove unnecessary imports * Fix a warning raising * Remove unnecessary f string * Add missing traceback import * Fix typo * Use new-style typing annotations, not comments
1 parent 8d355da commit d4ff7ae

File tree

16 files changed

+23
-30
lines changed

16 files changed

+23
-30
lines changed

docs/source/conf.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
# serve to show the default.
1818

1919
import os
20-
import sys
2120
from pathlib import Path
2221

2322
import pymc # isort:skip

pymc/backends/arviz.py

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,14 +26,11 @@
2626
import pymc
2727

2828
from pymc.aesaraf import extract_obs_data
29-
from pymc.model import modelcontext
29+
from pymc.model import Model, modelcontext
3030
from pymc.util import get_default_varnames
3131

3232
if TYPE_CHECKING:
33-
from typing import Set # pylint: disable=ungrouped-imports
34-
3533
from pymc.backends.base import MultiTrace # pylint: disable=invalid-name
36-
from pymc.model import Model
3734

3835
___all__ = [""]
3936

@@ -145,12 +142,10 @@ def insert(self, k: str, v, idx: int):
145142
class InferenceDataConverter: # pylint: disable=too-many-instance-attributes
146143
"""Encapsulate InferenceData specific logic."""
147144

148-
model = None # type: Optional[Model]
149-
nchains = None # type: int
150-
ndraws = None # type: int
151-
posterior_predictive = None # Type: Optional[Mapping[str, np.ndarray]]
152-
predictions = None # Type: Optional[Mapping[str, np.ndarray]]
153-
prior = None # Type: Optional[Mapping[str, np.ndarray]]
145+
model: Optional[Model] = None
146+
posterior_predictive: Optional[Mapping[str, np.ndarray]] = None
147+
predictions: Optional[Mapping[str, np.ndarray]] = None
148+
prior: Optional[Mapping[str, np.ndarray]] = None
154149

155150
def __init__(
156151
self,

pymc/backends/ndarray.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ def setup(self, draws, chain, sampler_vars=None) -> None:
8585
if self._stats is None:
8686
self._stats = []
8787
for sampler in sampler_vars:
88-
data = dict() # type: Dict[str, np.ndarray]
88+
data: Dict[str, np.ndarray] = dict()
8989
self._stats.append(data)
9090
for varname, dtype in sampler.items():
9191
data[varname] = np.zeros(draws, dtype=dtype)

pymc/data.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -301,7 +301,7 @@ class Minibatch(TensorVariable):
301301
>>> assert x.eval().shape == (2, 20, 20, 40, 10)
302302
"""
303303

304-
RNG = collections.defaultdict(list) # type: Dict[str, List[Any]]
304+
RNG: Dict[str, List[Any]] = collections.defaultdict(list)
305305

306306
@aesara.config.change_flags(compute_test_value="raise")
307307
def __init__(
@@ -708,7 +708,7 @@ def Data(
708708
xshape = x.shape
709709
# Register new dimension lengths
710710
for d, dname in enumerate(dims):
711-
if not dname in model.dim_lengths:
711+
if dname not in model.dim_lengths:
712712
model.add_coord(
713713
name=dname,
714714
# Note: Coordinate values can't be taken from

pymc/distributions/distribution.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,9 +63,9 @@
6363

6464
DIST_PARAMETER_TYPES: TypeAlias = Union[np.ndarray, int, float, TensorVariable]
6565

66-
vectorized_ppc = contextvars.ContextVar(
66+
vectorized_ppc: contextvars.ContextVar[Optional[Callable]] = contextvars.ContextVar(
6767
"vectorized_ppc", default=None
68-
) # type: contextvars.ContextVar[Optional[Callable]]
68+
)
6969

7070
PLATFORM = sys.platform
7171

pymc/gp/util.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def kmeans_inducing_points(n_inducing, X, **kmeans_kwargs):
136136
Xw = X / scaling
137137

138138
if "k_or_guess" in kmeans_kwargs:
139-
warn.UserWarning("Use `n_inducing` to set the `k_or_guess` parameter instead.")
139+
warnings.warn("Use `n_inducing` to set the `k_or_guess` parameter instead.")
140140

141141
Xu, distortion = kmeans(Xw, k_or_guess=n_inducing, **kmeans_kwargs)
142142
return Xu * scaling

pymc/model.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ def get_context(cls, error_if_none=True) -> Optional[T]:
188188
on the stack, or ``None``. If ``error_if_none`` is True (default),
189189
raise a ``TypeError`` instead of returning ``None``."""
190190
try:
191-
candidate = cls.get_contexts()[-1] # type: Optional[T]
191+
candidate: Optional[T] = cls.get_contexts()[-1]
192192
except IndexError as e:
193193
# Calling code expects to get a TypeError if the entity
194194
# is unfound, and there's too much to fix.
@@ -1093,7 +1093,7 @@ def set_dim(self, name: str, new_length: int, coord_values: Optional[Sequence] =
10931093
len_cvals = len(coord_values)
10941094
if len_cvals != new_length:
10951095
raise ShapeError(
1096-
f"Length of new coordinate values does not match the new dimension length.",
1096+
"Length of new coordinate values does not match the new dimension length.",
10971097
actual=len_cvals,
10981098
expected=new_length,
10991099
)
@@ -1292,7 +1292,7 @@ def register_rv(
12921292
# the length of the corresponding RV dimension.
12931293
if dims is not None:
12941294
for d, dname in enumerate(dims):
1295-
if not dname in self.dim_lengths:
1295+
if dname not in self.dim_lengths:
12961296
self.add_coord(dname, values=None, length=rv_var.shape[d])
12971297

12981298
if data is None:

pymc/model_graph.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ def model_to_networkx(
355355
356356
model_to_networkx(schools)
357357
"""
358-
if not "plain" in formatting:
358+
if "plain" not in formatting:
359359

360360
raise ValueError(f"Unsupported formatting for graph nodes: '{formatting}'. See docstring.")
361361

@@ -419,7 +419,7 @@ def model_to_graphviz(
419419
420420
model_to_graphviz(schools)
421421
"""
422-
if not "plain" in formatting:
422+
if "plain" not in formatting:
423423
raise ValueError(f"Unsupported formatting for graph nodes: '{formatting}'. See docstring.")
424424
if formatting != "plain":
425425
warnings.warn(

pymc/tests/distributions/test_discrete.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ def categorical_logpdf(value, p):
6969
if value >= 0 and value <= len(p):
7070
return floatX(np.log(np.moveaxis(p, -1, 0)[value]))
7171
else:
72-
return -inf
72+
return -np.inf
7373

7474

7575
def invlogit(x, eps=sys.float_info.epsilon):

pymc/tests/test_model.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414
import pickle
1515
import threading
16+
import traceback
1617
import unittest
1718
import warnings
1819

@@ -406,7 +407,7 @@ def test_multiple_observed_rv():
406407
assert not model["x"] == model["mu"]
407408
assert model["x"] == model["x"]
408409
assert model["x"] in model.observed_RVs
409-
assert not model["x"] in model.value_vars
410+
assert model["x"] not in model.value_vars
410411

411412

412413
def test_tempered_logp_dlogp():

pymc/tests/tuning/test_starting.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def test_mle_jacobian(bounded):
4242
def test_tune_not_inplace():
4343
orig_scaling = np.array([0.001, 0.1])
4444
returned_scaling = tune(orig_scaling, acc_rate=0.6)
45-
assert not returned_scaling is orig_scaling
45+
assert returned_scaling is not orig_scaling
4646
assert np.all(orig_scaling == np.array([0.001, 0.1]))
4747

4848

pymc/variational/inference.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,7 @@ def _infmean(input_array):
258258
)
259259
else:
260260
if n == 0:
261-
logger.info(f"Initialization only")
261+
logger.info("Initialization only")
262262
elif n < 10:
263263
logger.info(f"Finished [100%]: Loss = {scores[-1]:,.5g}")
264264
else:

pymc/variational/opvi.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1482,7 +1482,7 @@ def sample(
14821482

14831483
if random_seed is not None:
14841484
(random_seed,) = _get_seeds_per_chain(random_seed, 1)
1485-
samples = self.sample_dict_fn(draws, random_seed=random_seed) # type: dict
1485+
samples: dict = self.sample_dict_fn(draws, random_seed=random_seed)
14861486
points = ({name: records[i] for name, records in samples.items()} for i in range(draws))
14871487

14881488
trace = NDArray(

scripts/run_mypy.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def check_no_unexpected_results(mypy_lines: Iterator[str]):
144144
all_files = {
145145
str(fp).replace(str(DP_ROOT), "").strip(os.sep).replace(os.sep, "/")
146146
for fp in DP_ROOT.glob("pymc/**/*.py")
147-
if not "tests" in str(fp)
147+
if "tests" not in str(fp)
148148
}
149149
failing = set(df.reset_index().file.str.replace(os.sep, "/", regex=False))
150150
if not failing.issubset(all_files):

setup.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
import re
1615

1716
from codecs import open
1817
from os.path import dirname, join, realpath

setupegg.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
A setup.py script to use setuptools, which gives egg goodness, etc.
1818
"""
1919

20-
from setuptools import setup
2120

2221
with open("setup.py") as s:
2322
exec(s.read())

0 commit comments

Comments
 (0)