pipbreak 0.2.0__tar.gz → 0.2.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pipbreak
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Find the installed packages a dependency update breaks - the calls pip's version ranges let through.
5
5
  Author: Youssef Elaasri
6
6
  License-Expression: MIT
@@ -77,7 +77,7 @@ No configuration, no type stubs, zero dependencies. Python 3.10+.
77
77
  ([pretix#6722](https://github.com/pretix/pretix/issues/6722))
78
78
 
79
79
  The other three apps were NetBox, FlaskBB and healthchecks. On paperless-ngx (17,000 files),
80
- every error it reports is a real API mismatch: 7 on Linux, plus one Windows-only on Windows.
80
+ every error it reports is a real API mismatch: 7, on Windows and Linux alike.
81
81
  - **What it can't see:** arguments forwarded through `**kwargs`, methods on objects whose type is
82
82
  only known at runtime, binary (C extension) incompatibilities, and behaviour changes behind an
83
83
  unchanged API. It complements your tests; it doesn't replace them.
@@ -201,13 +201,18 @@ attribute.
201
201
  When the code only *declares* a type (a type hint, a return annotation, an `isinstance` check), the
202
202
  value may be a subclass, and frameworks attach data to instances from outside the class (Django's
203
203
  `request.user`). So only **method calls** are checked there, as a **warning** (API006): `engine.execute()`
204
- on a parameter typed `Engine`, after SQLAlchemy 2 removed `Engine.execute`.
204
+ on a parameter typed `Engine`, after SQLAlchemy 2 removed `Engine.execute`. It stays quiet when a loaded
205
+ subclass defines the method (parso's `Import` is always an `ImportName` or `ImportFrom`), for `Protocol`
206
+ types, and for an annotated `self` in a mixin (`def delete(self: BaseView)`).
205
207
 
206
208
  ## Avoiding false positives
207
209
 
208
210
  - Imports and calls under feature probes are skipped: `if hasattr(...)`, `sys.platform`,
209
211
  `sys.version_info`, `os.name`, `TYPE_CHECKING`, `try/except ImportError|AttributeError`, and
210
212
  flags assigned from these (`HAVE_FORK = hasattr(os, "fork")`).
213
+ - Names a library itself only defines under such a probe (tornado's `bind_unix_socket`, Unix only)
214
+ aren't reported as missing on other platforms, and neither are attributes the package sets on its
215
+ own modules at runtime (Django's test setup does `mail.outbox = []`).
211
216
  - Your own modules, relative imports, and names you reassign are never checked. A name bound to
212
217
  different things in one scope (or used as a loop/comprehension/lambda variable) isn't inferred.
213
218
  - Classes with a custom `__getattr__`/`__getattribute__`, a custom metaclass (ORMs, pydantic, enums),
@@ -56,7 +56,7 @@ No configuration, no type stubs, zero dependencies. Python 3.10+.
56
56
  ([pretix#6722](https://github.com/pretix/pretix/issues/6722))
57
57
 
58
58
  The other three apps were NetBox, FlaskBB and healthchecks. On paperless-ngx (17,000 files),
59
- every error it reports is a real API mismatch: 7 on Linux, plus one Windows-only on Windows.
59
+ every error it reports is a real API mismatch: 7, on Windows and Linux alike.
60
60
  - **What it can't see:** arguments forwarded through `**kwargs`, methods on objects whose type is
61
61
  only known at runtime, binary (C extension) incompatibilities, and behaviour changes behind an
62
62
  unchanged API. It complements your tests; it doesn't replace them.
@@ -180,13 +180,18 @@ attribute.
180
180
  When the code only *declares* a type (a type hint, a return annotation, an `isinstance` check), the
181
181
  value may be a subclass, and frameworks attach data to instances from outside the class (Django's
182
182
  `request.user`). So only **method calls** are checked there, as a **warning** (API006): `engine.execute()`
183
- on a parameter typed `Engine`, after SQLAlchemy 2 removed `Engine.execute`.
183
+ on a parameter typed `Engine`, after SQLAlchemy 2 removed `Engine.execute`. It stays quiet when a loaded
184
+ subclass defines the method (parso's `Import` is always an `ImportName` or `ImportFrom`), for `Protocol`
185
+ types, and for an annotated `self` in a mixin (`def delete(self: BaseView)`).
184
186
 
185
187
  ## Avoiding false positives
186
188
 
187
189
  - Imports and calls under feature probes are skipped: `if hasattr(...)`, `sys.platform`,
188
190
  `sys.version_info`, `os.name`, `TYPE_CHECKING`, `try/except ImportError|AttributeError`, and
189
191
  flags assigned from these (`HAVE_FORK = hasattr(os, "fork")`).
192
+ - Names a library itself only defines under such a probe (tornado's `bind_unix_socket`, Unix only)
193
+ aren't reported as missing on other platforms, and neither are attributes the package sets on its
194
+ own modules at runtime (Django's test setup does `mail.outbox = []`).
190
195
  - Your own modules, relative imports, and names you reassign are never checked. A name bound to
191
196
  different things in one scope (or used as a loop/comprehension/lambda variable) isn't inferred.
192
197
  - Classes with a custom `__getattr__`/`__getattribute__`, a custom metaclass (ORMs, pydantic, enums),
@@ -1,4 +1,4 @@
1
1
  from .checker import Finding, check_paths, check_source
2
2
 
3
3
  __all__ = ["Finding", "check_paths", "check_source"]
4
- __version__ = "0.2.0"
4
+ __version__ = "0.2.2"
@@ -128,7 +128,7 @@ class Environment:
128
128
  sub = self.module(f"{obj.__name__}.{name}")
129
129
  if sub is not None:
130
130
  return sub
131
- if name in stub_names(obj):
131
+ if name in stub_names(obj) or name in conditional_names(obj) or name in assigned_from_outside(obj):
132
132
  return UNKNOWN
133
133
  return MISSING
134
134
 
@@ -174,6 +174,92 @@ def stub_names(module) -> set[str]:
174
174
  return _stub_cache[file]
175
175
 
176
176
 
177
+ _conditional_cache: dict[str, set[str]] = {}
178
+
179
+
180
+ def conditional_names(module) -> set[str]:
181
+ """Names a module only defines on some platforms or versions, so their absence here proves
182
+ nothing: tornado.netutil defines `bind_unix_socket` under `if hasattr(socket, "AF_UNIX"):`."""
183
+ file = getattr(module, "__file__", None)
184
+ if not isinstance(file, str) or not file.endswith(".py"):
185
+ return set()
186
+ if file not in _conditional_cache:
187
+ try:
188
+ with tokenize.open(file) as f:
189
+ tree = ast.parse(f.read())
190
+ except (OSError, SyntaxError, ValueError, UnicodeDecodeError):
191
+ tree = None
192
+ names: set[str] = set()
193
+ if tree is not None:
194
+ flags = feature_flags(tree)
195
+
196
+ def defined(stmts):
197
+ for stmt in stmts:
198
+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
199
+ names.add(stmt.name)
200
+ elif isinstance(stmt, (ast.Assign, ast.AnnAssign)):
201
+ targets = stmt.targets if isinstance(stmt, ast.Assign) else [stmt.target]
202
+ names.update(n.id for t in targets for n in ast.walk(t) if isinstance(n, ast.Name))
203
+ elif isinstance(stmt, (ast.Import, ast.ImportFrom)):
204
+ names.update((a.asname or a.name).split(".")[0] for a in stmt.names)
205
+ elif isinstance(stmt, ast.If):
206
+ defined(stmt.body)
207
+ defined(stmt.orelse)
208
+ elif isinstance(stmt, ast.Try):
209
+ defined(stmt.body)
210
+ for handler in stmt.handlers:
211
+ defined(handler.body)
212
+
213
+ def visit(stmts):
214
+ for stmt in stmts:
215
+ if isinstance(stmt, ast.If):
216
+ if is_feature_probe(stmt.test, flags):
217
+ defined(stmt.body)
218
+ defined(stmt.orelse)
219
+ else:
220
+ visit(stmt.body)
221
+ visit(stmt.orelse)
222
+ elif isinstance(stmt, ast.Try) and caught_names(stmt) & GUARD_ERRORS:
223
+ defined(stmt.body)
224
+ for handler in stmt.handlers:
225
+ defined(handler.body)
226
+
227
+ visit(tree.body)
228
+ _conditional_cache[file] = names
229
+ return _conditional_cache[file]
230
+
231
+
232
+ _assigned_cache: dict[str, dict[str, set[str]]] = {}
233
+ ATTRIBUTE_STORE = re.compile(r"\b(\w+)\.(\w+)[ \t]*=(?!=)")
234
+
235
+
236
+ def assigned_from_outside(module) -> set[str]:
237
+ """Attributes other modules of the same package set on this one at runtime: Django's test
238
+ setup does `mail.outbox = []`, so `django.core.mail.outbox` exists while tests run.
239
+
240
+ Each package is read once, into {module's last name: attributes stored on it}.
241
+ """
242
+ name = getattr(module, "__name__", "")
243
+ top, _, rest = name.partition(".")
244
+ if not rest:
245
+ return set()
246
+ if top not in _assigned_cache:
247
+ index: dict[str, set[str]] = defaultdict(set)
248
+ root = getattr(sys.modules.get(top), "__file__", None)
249
+ if isinstance(root, str) and os.path.basename(root) == "__init__.py":
250
+ for i, path in enumerate(Path(root).parent.rglob("*.py")):
251
+ if i >= 3000: # huge packages (torch): not worth reading everything
252
+ break
253
+ try:
254
+ text = path.read_text(encoding="utf-8", errors="replace")
255
+ except OSError:
256
+ continue
257
+ for owner, attr in ATTRIBUTE_STORE.findall(text):
258
+ index[owner].add(attr)
259
+ _assigned_cache[top] = index
260
+ return _assigned_cache[top].get(name.rsplit(".", 1)[-1], set())
261
+
262
+
177
263
  def packages_distributions() -> dict[str, list[str]]:
178
264
  """Top-level module -> distributions providing it.
179
265
 
@@ -462,6 +548,29 @@ def assigned_attrs(tree: ast.AST) -> set[str] | None:
462
548
  _instance_attrs_cache: dict = {}
463
549
 
464
550
 
551
+ def subclass_defines(cls, attr: str, limit: int = 2000) -> bool:
552
+ """Whether a loaded subclass of cls has `attr`."""
553
+ seen: set[int] = set()
554
+ todo = [cls]
555
+ while todo and len(seen) < limit:
556
+ current = todo.pop()
557
+ try:
558
+ subs = type.__subclasses__(current) if isinstance(current, type) else []
559
+ except TypeError:
560
+ continue
561
+ for sub in subs:
562
+ if id(sub) in seen:
563
+ continue
564
+ seen.add(id(sub))
565
+ try:
566
+ if attr in vars(sub):
567
+ return True
568
+ except TypeError:
569
+ pass
570
+ todo.append(sub)
571
+ return False
572
+
573
+
465
574
  def instance_attrs(cls) -> tuple[set[str], bool] | None:
466
575
  """Attribute names an instance of cls can have, and whether that list is certain.
467
576
 
@@ -1041,7 +1150,13 @@ class FileChecker(ast.NodeVisitor):
1041
1150
  if args is not None:
1042
1151
  positional = args.posonlyargs + args.args
1043
1152
  for a in positional + args.kwonlyargs:
1044
- sources[a.arg].append(self.annotation_type(a.annotation))
1153
+ value = self.annotation_type(a.annotation)
1154
+ if (positional and a is positional[0] and a.arg in ("self", "cls") and type(value) is Instance
1155
+ and not value.exact):
1156
+ # `def muldelete(self: BaseView, ...)` in a mixin: the methods it calls come
1157
+ # from the class it's mixed into, not from the annotated base.
1158
+ value = Instance(value.cls, exact=False)
1159
+ sources[a.arg].append(value)
1045
1160
  for a in (args.vararg, args.kwarg):
1046
1161
  if a:
1047
1162
  sources[a.arg].append(UNTYPED)
@@ -1256,9 +1371,17 @@ class FileChecker(ast.NodeVisitor):
1256
1371
  attr = expr.attr
1257
1372
  if id(expr) not in self.call_funcs or attr.startswith("__"):
1258
1373
  return
1374
+ # A Protocol only lists what the code needs; implementations have more (jsonschema's
1375
+ # Validator and `descend`).
1376
+ if getattr(cls, "_is_protocol", False):
1377
+ return
1259
1378
  known = instance_attrs(cls)
1260
1379
  if known is None or attr in known[0]:
1261
1380
  return
1381
+ # A base class the real objects are subclasses of: parso's `Import` is always an
1382
+ # `ImportName` or `ImportFrom`, which define `get_paths`.
1383
+ if subclass_defines(cls, attr):
1384
+ return
1262
1385
  module = owner_module(cls)
1263
1386
  hint = suggest(attr, known[0])
1264
1387
  self.report(expr, "warning", "API006",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pipbreak
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Find the installed packages a dependency update breaks - the calls pip's version ranges let through.
5
5
  Author: Youssef Elaasri
6
6
  License-Expression: MIT
@@ -77,7 +77,7 @@ No configuration, no type stubs, zero dependencies. Python 3.10+.
77
77
  ([pretix#6722](https://github.com/pretix/pretix/issues/6722))
78
78
 
79
79
  The other three apps were NetBox, FlaskBB and healthchecks. On paperless-ngx (17,000 files),
80
- every error it reports is a real API mismatch: 7 on Linux, plus one Windows-only on Windows.
80
+ every error it reports is a real API mismatch: 7, on Windows and Linux alike.
81
81
  - **What it can't see:** arguments forwarded through `**kwargs`, methods on objects whose type is
82
82
  only known at runtime, binary (C extension) incompatibilities, and behaviour changes behind an
83
83
  unchanged API. It complements your tests; it doesn't replace them.
@@ -201,13 +201,18 @@ attribute.
201
201
  When the code only *declares* a type (a type hint, a return annotation, an `isinstance` check), the
202
202
  value may be a subclass, and frameworks attach data to instances from outside the class (Django's
203
203
  `request.user`). So only **method calls** are checked there, as a **warning** (API006): `engine.execute()`
204
- on a parameter typed `Engine`, after SQLAlchemy 2 removed `Engine.execute`.
204
+ on a parameter typed `Engine`, after SQLAlchemy 2 removed `Engine.execute`. It stays quiet when a loaded
205
+ subclass defines the method (parso's `Import` is always an `ImportName` or `ImportFrom`), for `Protocol`
206
+ types, and for an annotated `self` in a mixin (`def delete(self: BaseView)`).
205
207
 
206
208
  ## Avoiding false positives
207
209
 
208
210
  - Imports and calls under feature probes are skipped: `if hasattr(...)`, `sys.platform`,
209
211
  `sys.version_info`, `os.name`, `TYPE_CHECKING`, `try/except ImportError|AttributeError`, and
210
212
  flags assigned from these (`HAVE_FORK = hasattr(os, "fork")`).
213
+ - Names a library itself only defines under such a probe (tornado's `bind_unix_socket`, Unix only)
214
+ aren't reported as missing on other platforms, and neither are attributes the package sets on its
215
+ own modules at runtime (Django's test setup does `mail.outbox = []`).
211
216
  - Your own modules, relative imports, and names you reassign are never checked. A name bound to
212
217
  different things in one scope (or used as a loop/comprehension/lambda variable) isn't inferred.
213
218
  - Classes with a custom `__getattr__`/`__getattribute__`, a custom metaclass (ORMs, pydantic, enums),
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pipbreak"
7
- version = "0.2.0"
7
+ version = "0.2.2"
8
8
  description = "Find the installed packages a dependency update breaks - the calls pip's version ranges let through."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -718,15 +718,87 @@ class DeclaredTypes(unittest.TestCase):
718
718
 
719
719
  def import_optional_dependency(name, errors="raise"):
720
720
  return importlib.import_module(name)
721
+
722
+ class Node:
723
+ def get_root(self): pass
724
+
725
+ class ImportNode(Node):
726
+ def get_paths(self): pass
727
+
728
+ class Validates(typing.Protocol):
729
+ def iter_errors(self): ...
730
+ '''))
731
+ Path(cls.tmp.name, "condlib.py").write_text(textwrap.dedent('''
732
+ import sys
733
+ if sys.platform == "no-such-platform":
734
+ def unix_only(): pass
721
735
  '''))
736
+ pkg = Path(cls.tmp.name, "outlib")
737
+ pkg.mkdir()
738
+ (pkg / "__init__.py").write_text("")
739
+ (pkg / "mail.py").write_text("def send(): pass\n")
740
+ (pkg / "testing.py").write_text("from outlib import mail\nmail.outbox = []\n")
722
741
  sys.path.insert(0, cls.tmp.name)
723
742
 
724
743
  @classmethod
725
744
  def tearDownClass(cls):
726
745
  sys.path.remove(cls.tmp.name)
727
- sys.modules.pop("typedlib", None)
746
+ for name in ("typedlib", "condlib", "outlib", "outlib.mail", "outlib.testing"):
747
+ sys.modules.pop(name, None)
728
748
  cls.tmp.cleanup()
729
749
 
750
+ def test_method_a_subclass_defines_is_not_reported(self):
751
+ # jedi on parso: an `Import` node is always an ImportName or ImportFrom.
752
+ source = """
753
+ from typedlib import Node
754
+ def f(node: Node):
755
+ node.get_paths()
756
+ node.no_such_method()
757
+ """
758
+ self.assertEqual([(f.code, f.line) for f in check_source(textwrap.dedent(source))], [("API006", 5)])
759
+
760
+ def test_keyword_only_parameters_without_positional_ones(self):
761
+ source = """
762
+ from typedlib import Engine
763
+ def f(*, engine: Engine):
764
+ engine.execute()
765
+ """
766
+ self.assertEqual(codes(source), ["API006"])
767
+
768
+ def test_protocol_types_are_not_checked(self):
769
+ source = """
770
+ from typedlib import Validates
771
+ def f(v: Validates):
772
+ v.descend()
773
+ """
774
+ self.assertEqual(codes(source), [])
775
+
776
+ def test_annotated_self_in_a_mixin_is_not_checked(self):
777
+ source = """
778
+ from typedlib import Engine
779
+ class DeleteMixin:
780
+ def delete(self: Engine):
781
+ self.post_delete()
782
+ """
783
+ self.assertEqual(codes(source), [])
784
+
785
+ def test_names_a_module_only_defines_on_some_platforms(self):
786
+ source = """
787
+ import condlib
788
+ condlib.unix_only()
789
+ condlib.nowhere()
790
+ """
791
+ self.assertEqual([(f.code, f.line) for f in check_source(textwrap.dedent(source))], [("API002", 4)])
792
+
793
+ def test_attributes_the_package_sets_at_runtime(self):
794
+ # Django's test setup does `mail.outbox = []`.
795
+ source = """
796
+ from outlib import mail
797
+ mail.outbox
798
+ mail.inbox
799
+ """
800
+ self.assertEqual([(f.code, f.line) for f in check_source(textwrap.dedent(source))], [("API002", 4)])
801
+
730
802
  def test_method_missing_from_a_type_hint(self):
731
803
  source = """
732
804
  from typedlib import Engine
File without changes
File without changes
File without changes
File without changes
File without changes