pythonqtside 1.1.12__py3-none-any.whl

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.
Files changed (42) hide show
  1. pythonqtside/Qt.py +14 -0
  2. pythonqtside/QtCore.py +14 -0
  3. pythonqtside/QtGui.py +14 -0
  4. pythonqtside/QtNetwork.py +14 -0
  5. pythonqtside/QtOpenGL.py +14 -0
  6. pythonqtside/QtSvg.py +14 -0
  7. pythonqtside/QtUiTools.py +14 -0
  8. pythonqtside/QtWidgets.py +14 -0
  9. pythonqtside/QtXmlPatterns.py +14 -0
  10. pythonqtside/__init__.py +34 -0
  11. pythonqtside/_app.py +319 -0
  12. pythonqtside/_app_cleanup.py +216 -0
  13. pythonqtside/_app_conversions.py +106 -0
  14. pythonqtside/_app_dialogs.py +74 -0
  15. pythonqtside/_app_flags.py +79 -0
  16. pythonqtside/_app_imports.py +146 -0
  17. pythonqtside/_app_keywords.py +210 -0
  18. pythonqtside/_app_native.py +404 -0
  19. pythonqtside/_app_proxy.py +43 -0
  20. pythonqtside/_app_source.py +110 -0
  21. pythonqtside/_differences.json +9808 -0
  22. pythonqtside/_flags.json +210 -0
  23. pythonqtside/_implicit_conversions.json +1975 -0
  24. pythonqtside/_inventory.json +115478 -0
  25. pythonqtside/_keywords.json +1 -0
  26. pythonqtside/_out_parameters.json +465 -0
  27. pythonqtside/_qtwidgets.json +202 -0
  28. pythonqtside/_routing.py +95 -0
  29. pythonqtside/compat.py +44 -0
  30. pythonqtside/tooling/__init__.py +2 -0
  31. pythonqtside/tooling/conversions.py +433 -0
  32. pythonqtside/tooling/differences.py +290 -0
  33. pythonqtside/tooling/flags.py +156 -0
  34. pythonqtside/tooling/inventory.py +149 -0
  35. pythonqtside/tooling/join.py +184 -0
  36. pythonqtside/tooling/keywords.py +259 -0
  37. pythonqtside/tooling/surface.py +191 -0
  38. pythonqtside-1.1.12.dist-info/METADATA +468 -0
  39. pythonqtside-1.1.12.dist-info/RECORD +42 -0
  40. pythonqtside-1.1.12.dist-info/WHEEL +4 -0
  41. pythonqtside-1.1.12.dist-info/licenses/LICENSE +201 -0
  42. pythonqtside-1.1.12.dist-info/licenses/NOTICE +7 -0
@@ -0,0 +1,184 @@
1
+ # this_file: src/pythonqtside/tooling/join.py
2
+ """Join factual surfaces; unknown capture details remain explicitly unknown."""
3
+
4
+ from .surface import Surface, effective_classes, extract
5
+
6
+ MODULES = (
7
+ "QtCore",
8
+ "QtGui",
9
+ "QtWidgets",
10
+ "QtNetwork",
11
+ "QtOpenGL",
12
+ "QtSvg",
13
+ "QtUiTools",
14
+ "QtXmlPatterns",
15
+ )
16
+ NATIVE_MODULES = tuple(m for m in MODULES if m != "QtWidgets") + ("private", "Qt")
17
+ STATUSES = ("native_same_module", "native_other_module", "private_only", "missing")
18
+ _EMPTY = extract("class Absent: pass")["classes"]["Absent"]
19
+
20
+
21
+ def _route(module: str, name: str, native: dict[str, Surface], kind: str) -> dict:
22
+ found = sorted(m for m, data in native.items() if name in data[kind])
23
+ # Prefer the canonical family, then public families, combined Qt, finally private.
24
+ order = [module, "QtGui"] if module == "QtWidgets" else [module]
25
+ order += [m for m in NATIVE_MODULES if m not in {"Qt", "private"}] + [
26
+ "Qt",
27
+ "private",
28
+ ]
29
+ target = next((m for m in order if m in found), None)
30
+ status = "missing" if target is None else "native_other_module"
31
+ if target == module:
32
+ status = "native_same_module"
33
+ elif target == "private":
34
+ status = "private_only"
35
+ return {"native_module": target, "native_locations": found, "status": status}
36
+
37
+
38
+ def _nested_enums(pyside: Surface, native: Surface) -> dict:
39
+ result = {}
40
+ for name in sorted(pyside["enums"].keys() | native["enums"].keys()):
41
+ expected = pyside["enums"].get(name, set())
42
+ actual = native["enums"].get(name, set())
43
+ opaque = name in native["opaque_types"]
44
+ result[name] = {
45
+ "native_layout": "opaque_type"
46
+ if opaque
47
+ else "nested"
48
+ if name in native["enums"]
49
+ else "absent",
50
+ "members_only_pyside": None if opaque else sorted(expected - actual),
51
+ "members_only_native": None if opaque else sorted(actual - expected),
52
+ }
53
+ return result
54
+
55
+
56
+ TUPLE_PREFIXES = ("typing.Tuple[", "Tuple[", "tuple[")
57
+
58
+
59
+ def _tuple_returns(pyside: Surface, native: Surface) -> dict:
60
+ """PySide2 tuple results versus the same-name native declarations (out-parameters)."""
61
+ result = {}
62
+ for name, overloads in sorted(pyside["signatures"].items()):
63
+ returns = sorted(
64
+ {
65
+ s["returns"]
66
+ for s in overloads
67
+ if (s["returns"] or "").startswith(TUPLE_PREFIXES)
68
+ }
69
+ )
70
+ if returns:
71
+ result[name] = {
72
+ "pyside_returns": returns,
73
+ "pyside_overloads": overloads,
74
+ "native_overloads": native["signatures"].get(name),
75
+ }
76
+ return result
77
+
78
+
79
+ def _bool_predicates(native: Surface) -> list[str]:
80
+ return sorted(
81
+ name
82
+ for name, overloads in native["signatures"].items()
83
+ if any(not s["parameters"] and s["returns"] == "bool" for s in overloads)
84
+ )
85
+
86
+
87
+ def differences(pyside: Surface, native: Surface) -> dict:
88
+ """A name difference does not establish callable, value or dispatch compatibility."""
89
+ pa, na = (
90
+ set(pyside["attributes"]) | pyside["properties"],
91
+ set(native["attributes"]) | native["properties"],
92
+ )
93
+ result = {
94
+ "methods_only_pyside": sorted(pyside["methods"] - native["methods"]),
95
+ "methods_only_native": sorted(native["methods"] - pyside["methods"]),
96
+ "attributes_only_pyside": sorted(pa - na),
97
+ "attributes_only_native": sorted(na - pa),
98
+ "native_attributes_for_pyside_accessors": sorted(pyside["getters"] & na),
99
+ "enum_members_only_pyside": sorted(
100
+ pyside["enum_members"] - na - native["enum_members"]
101
+ ),
102
+ "enum_members_only_native": sorted(
103
+ native["enum_members"] - pa - pyside["enum_members"]
104
+ ),
105
+ "enum_members_only_native_candidates": sorted(
106
+ native["enum_candidates"]
107
+ - native["enum_members"]
108
+ - pa
109
+ - pyside["enum_members"]
110
+ ),
111
+ "nested_enums": _nested_enums(pyside, native),
112
+ "tuple_returns": _tuple_returns(pyside, native),
113
+ "nested_classes_only_pyside": sorted(
114
+ pyside["nested_classes"].keys()
115
+ - native["nested_classes"].keys()
116
+ - native["opaque_types"]
117
+ ),
118
+ "nested_classes_only_native": sorted(
119
+ native["nested_classes"].keys() - pyside["nested_classes"].keys()
120
+ ),
121
+ }
122
+ # Predicates are recorded only where a tuple result may need an ok value.
123
+ result["native_bool_predicates"] = (
124
+ _bool_predicates(native) if result["tuple_returns"] else []
125
+ )
126
+ result["nested_classes"] = {
127
+ n: class_details(cls, native["nested_classes"].get(n))
128
+ for n, cls in sorted(pyside["nested_classes"].items())
129
+ }
130
+ return result
131
+
132
+
133
+ def counts(surface: Surface) -> dict[str, int]:
134
+ return {
135
+ name: len(surface[name])
136
+ for name in (
137
+ "methods",
138
+ "properties",
139
+ "attributes",
140
+ "enums",
141
+ "enum_members",
142
+ "opaque_types",
143
+ "nested_classes",
144
+ "constructors",
145
+ )
146
+ }
147
+
148
+
149
+ def class_details(expected: Surface, actual: Surface | None) -> dict:
150
+ return {
151
+ "stub_helper": expected["stub_helper"],
152
+ "counts": {
153
+ "pyside": counts(expected),
154
+ "native": counts(actual) if actual else None,
155
+ },
156
+ "constructors": {
157
+ "pyside": expected["constructors"],
158
+ "native": actual["constructors"] if actual else None,
159
+ },
160
+ "differences": differences(expected, actual or _EMPTY),
161
+ }
162
+
163
+
164
+ def join_surfaces(pyside: dict[str, Surface], native: dict[str, Surface]) -> dict:
165
+ upstream_classes = effective_classes(pyside)
166
+ native_classes = effective_classes(native)
167
+ result = {}
168
+ for module, data in sorted(pyside.items()):
169
+ classes = {}
170
+ for name in sorted(data["classes"]):
171
+ route = _route(module, name, native, "classes")
172
+ expected = upstream_classes[f"{module}.{name}"]
173
+ actual = native_classes.get(f"{route['native_module']}.{name}")
174
+ classes[name] = route | class_details(expected, actual)
175
+ result[module] = {
176
+ "classes": classes,
177
+ "members": {
178
+ n: _route(module, n, native, "members") for n in sorted(data["members"])
179
+ },
180
+ "summary": {
181
+ s: sum(c["status"] == s for c in classes.values()) for s in STATUSES
182
+ },
183
+ }
184
+ return result
@@ -0,0 +1,259 @@
1
+ # this_file: src/pythonqtside/tooling/keywords.py
2
+ """Measure PySide2 keyword parameters for native PythonQt calls.
3
+
4
+ FontLab's PythonQt rejects every keyword argument to a native constructor or method
5
+ ("called slot does not support kwargs"; issue 104 evidence pqs-g04/probe_keywords.json).
6
+ PySide2 accepts its declared parameter names. This command reads the PySide2 and native
7
+ stubs the inventory pins (SHA256-verified) and writes, per routed class, the PySide2
8
+ parameter names of every constructor and method overload, plus the Qt 5.15 declaration
9
+ defaults that Echopy's native docstrings quote, where they are plain literals.
10
+ """
11
+
12
+ import argparse
13
+ import ast
14
+ import hashlib
15
+ import json
16
+ import re
17
+ from pathlib import Path
18
+
19
+ from .conversions import _effective, _route, declarations, load_sources, pack
20
+
21
+ PACKAGE = Path(__file__).resolve().parents[1]
22
+ LIMITATIONS = [
23
+ "FontLab 9 PythonQt rejects keyword arguments on every native constructor and method measured (pqs-g04/probe_keywords.json).",
24
+ "Parameter names come from the PySide2 5.15.2.1 stubs; they mirror the C++ declarations except where PySide2 drops out-parameters.",
25
+ "Tuple-returning PySide2 methods are listed only when _out_parameters.json adapts them; the rest drop out-parameters and are omitted.",
26
+ "Gap defaults are Qt 5.15 declaration defaults quoted in Echopy's native docstrings: nullptr, QString(), true/false, numbers, or Class::Member of a routed class (resolved natively at call time; unresolved means no mapping).",
27
+ "Constructors have no quoted declarations, so a constructor keyword call cannot skip a parameter.",
28
+ "Entries repeat per routed subclass: native stubs record no Qt base chain.",
29
+ ]
30
+ LINK = re.compile(r"\[([^\]]*)\]\([^)]*\)")
31
+ LITERALS = {
32
+ "nullptr": None,
33
+ "Q_NULLPTR": None,
34
+ "QString()": "",
35
+ "true": True,
36
+ "false": False,
37
+ }
38
+
39
+
40
+ def _literal(text: str, pointer: bool, owners: dict[str, str]) -> tuple[bool, object]:
41
+ """(known, value) for a C++ default; pointers treat 0 as None.
42
+
43
+ `Qt::AlignLeft` or `QLineEdit::Normal` become {"native": "QtGui.QLineEdit.Normal"}
44
+ when the owner class is routed; the runtime resolves the path or declines.
45
+ """
46
+ text = text.strip()
47
+ member = re.fullmatch(r"(\w+)::(\w+)", text)
48
+ if member and member.group(1) in owners:
49
+ return True, {
50
+ "native": f"{owners[member.group(1)]}.{member.group(1)}.{member.group(2)}"
51
+ }
52
+ if text in LITERALS:
53
+ return True, LITERALS[text]
54
+ if pointer and text in {"0", "NULL"}:
55
+ return True, None
56
+ if re.fullmatch(r"-?\d+", text):
57
+ return True, int(text)
58
+ if re.fullmatch(r"-?\d+\.\d*f?", text):
59
+ return True, float(text.rstrip("f"))
60
+ return False, None
61
+
62
+
63
+ def _split(params: str) -> list[str]:
64
+ """Top-level commas only: `QString()` and template arguments stay whole."""
65
+ parts, depth, current = [], 0, ""
66
+ for char in params:
67
+ depth += char in "(<"
68
+ depth -= char in ")>"
69
+ if char == "," and depth == 0:
70
+ parts.append(current)
71
+ current = ""
72
+ else:
73
+ current += char
74
+ return [p for p in (*parts, current) if p.strip()]
75
+
76
+
77
+ def qt_defaults(docstring: str, method: str, owners: dict[str, str]) -> list[dict]:
78
+ """Per quoted Qt declaration of `method`: {name: literal} for literal defaults."""
79
+ result = []
80
+ for line in docstring.splitlines():
81
+ if not line.startswith("### "):
82
+ continue
83
+ line = LINK.sub(r"\1", line).replace("\\", "")
84
+ match = re.search(rf"\w+::{re.escape(method)}\((.*)\)", line)
85
+ if match is None:
86
+ continue
87
+ found = {}
88
+ for param in _split(match.group(1)):
89
+ named = re.search(r"(\*?)\*(\w+)\*\s*(?:=\s*(.+))?$", param.strip())
90
+ if named and named.group(3) is not None:
91
+ known, value = _literal(named.group(3), bool(named.group(1)), owners)
92
+ if known:
93
+ found[named.group(2)] = value
94
+ result.append(found)
95
+ return result
96
+
97
+
98
+ def native_docstrings(source: bytes) -> dict[str, dict[str, str]]:
99
+ """Class -> method -> docstring from one native Echopy stub."""
100
+ result = {}
101
+ for node in ast.parse(source).body:
102
+ if isinstance(node, ast.ClassDef):
103
+ result[node.name] = {
104
+ item.name: ast.get_docstring(item) or ""
105
+ for item in node.body
106
+ if isinstance(item, ast.FunctionDef)
107
+ }
108
+ return result
109
+
110
+
111
+ def _agreed(headings: list[dict]) -> dict:
112
+ """Defaults every quoted declaration agrees on (overloads may disagree)."""
113
+ if not headings:
114
+ return {}
115
+ names = set.intersection(*(set(h) for h in headings))
116
+ return {
117
+ n: headings[0][n]
118
+ for n in sorted(names)
119
+ if all(h[n] == headings[0][n] for h in headings)
120
+ }
121
+
122
+
123
+ def _overloads(overloads: list[dict], defaults: dict) -> list[dict]:
124
+ shapes = []
125
+ for overload in overloads:
126
+ names = [p[0] for p in overload["parameters"]]
127
+ shape = {
128
+ "parameters": names,
129
+ "required": overload["required"],
130
+ "defaults": {n: defaults[n] for n in names if n in defaults},
131
+ }
132
+ if names and shape not in shapes:
133
+ shapes.append(shape)
134
+ return shapes
135
+
136
+
137
+ def _tuple_methods(inventory: dict, key: str) -> set[str]:
138
+ module, _, name = key.partition(".")
139
+ record = inventory["modules"][module]["classes"][name]
140
+ return set(record["differences"].get("tuple_returns", {}))
141
+
142
+
143
+ def _adapted(out_parameters: dict, native_key: str) -> set[str]:
144
+ return {
145
+ m
146
+ for kind in ("predicate", "bool_result")
147
+ for m in out_parameters.get(kind, {}).get(native_key, {})
148
+ }
149
+
150
+
151
+ def _out_defaults(out_parameters: dict, native_key: str, method: str) -> dict:
152
+ """Defaults the BoolResult adapter already uses for PySide2-omittable parameters."""
153
+ entry = out_parameters.get("bool_result", {}).get(native_key, {}).get(method)
154
+ return dict(entry["defaults"]) if entry else {}
155
+
156
+
157
+ def analyze(
158
+ inventory: dict,
159
+ pyside_sources: dict[str, bytes],
160
+ native_sources: dict[str, bytes],
161
+ inventory_sha256: str,
162
+ *,
163
+ out_parameters: dict,
164
+ ) -> dict:
165
+ pyside = {m: declarations(s) for m, s in pyside_sources.items()}
166
+ docs = {m: native_docstrings(s) for m, s in native_sources.items()}
167
+ owners = {"Qt": "QtCore"}
168
+ for data in inventory["modules"].values():
169
+ for name, record in sorted(data["classes"].items()):
170
+ if record["native_module"]:
171
+ owners.setdefault(name, record["native_module"])
172
+ classes, omitted = {}, {}
173
+ for module, decls in sorted(pyside.items()):
174
+ for name in sorted(decls):
175
+ key = f"{module}.{name}"
176
+ route = _route(inventory, key)
177
+ if route is None:
178
+ continue
179
+ native_key = f"{route['native_module']}.{name}"
180
+ native_docs = docs.get(route["native_module"], {}).get(name, {})
181
+ tuples = _tuple_methods(inventory, key) - _adapted(
182
+ out_parameters, native_key
183
+ )
184
+ methods = {"__init__": decls[name]["methods"].get("__init__", [])}
185
+ methods |= {
186
+ m: o
187
+ for m, o in _effective(pyside, key).items()
188
+ if not m.startswith("_")
189
+ }
190
+ for method, overloads in sorted(methods.items()):
191
+ if method in tuples:
192
+ omitted.setdefault(native_key, []).append(method)
193
+ continue
194
+ defaults = _agreed(
195
+ qt_defaults(native_docs.get(method, ""), method, owners)
196
+ )
197
+ defaults |= _out_defaults(out_parameters, native_key, method)
198
+ shapes = _overloads(overloads, {} if method == "__init__" else defaults)
199
+ if shapes:
200
+ static = method != "__init__" and all(
201
+ o["static"] for o in overloads
202
+ )
203
+ classes.setdefault(native_key, {})[method] = {
204
+ "static": static,
205
+ "overloads": shapes,
206
+ }
207
+ counts = {
208
+ "classes": len(classes),
209
+ "methods": sum(len(m) for m in classes.values()),
210
+ "constructors": sum("__init__" in m for m in classes.values()),
211
+ "gap_defaults": sum(
212
+ len(o["defaults"])
213
+ for m in classes.values()
214
+ for e in m.values()
215
+ for o in e["overloads"]
216
+ ),
217
+ "omitted_tuple_methods": sum(len(v) for v in omitted.values()),
218
+ }
219
+ return {
220
+ "schema_version": 1,
221
+ "inventory_sha256": inventory_sha256,
222
+ "limitations": LIMITATIONS,
223
+ "counts": counts,
224
+ "classes": classes,
225
+ "omitted": omitted,
226
+ }
227
+
228
+
229
+ def main() -> None:
230
+ parser = argparse.ArgumentParser(description=__doc__)
231
+ parser.add_argument("--echopy", type=Path, default=Path("../fontlab-echopy"))
232
+ parser.add_argument("--inventory", type=Path, default=PACKAGE / "_inventory.json")
233
+ parser.add_argument(
234
+ "--out-parameters", type=Path, default=PACKAGE / "_out_parameters.json"
235
+ )
236
+ parser.add_argument("--output", type=Path, default=PACKAGE / "_keywords.json")
237
+ args = parser.parse_args()
238
+ data = args.inventory.read_bytes()
239
+ inventory = json.loads(data)
240
+ pyside, native = load_sources(args.echopy, inventory)
241
+ out_parameters = json.loads(args.out_parameters.read_text(encoding="utf-8"))
242
+ report = analyze(
243
+ inventory,
244
+ pyside,
245
+ native,
246
+ hashlib.sha256(data).hexdigest(),
247
+ out_parameters=out_parameters,
248
+ )
249
+ args.output.write_text(
250
+ json.dumps(pack(report), sort_keys=True, separators=(",", ":")) + "\n",
251
+ encoding="utf-8",
252
+ )
253
+ digest = hashlib.sha256(args.output.read_bytes()).hexdigest()
254
+ print(f"{args.output.name}: {args.output.stat().st_size} bytes; SHA256 {digest}")
255
+ print(json.dumps(report["counts"], sort_keys=True))
256
+
257
+
258
+ if __name__ == "__main__":
259
+ main()
@@ -0,0 +1,191 @@
1
+ # this_file: src/pythonqtside/tooling/surface.py
2
+ """Extract declarations with ast, without executing stubs or their imports."""
3
+
4
+ import ast
5
+ from typing import Any
6
+
7
+ Surface = dict[str, Any]
8
+
9
+
10
+ def _shape(node: ast.FunctionDef | ast.AsyncFunctionDef) -> dict[str, int | bool]:
11
+ """Retain overload arities, not copied signature text or claimed dispatch."""
12
+ args = node.args
13
+ positional = args.posonlyargs + args.args
14
+ receiver = bool(positional and positional[0].arg in {"self", "cls"})
15
+ return {
16
+ "required_positional": max(0, len(positional) - len(args.defaults) - receiver),
17
+ "optional_positional": len(args.defaults),
18
+ "required_keyword_only": args.kw_defaults.count(None),
19
+ "optional_keyword_only": len(args.kw_defaults) - args.kw_defaults.count(None),
20
+ "varargs": args.vararg is not None,
21
+ "kwargs": args.kwarg is not None,
22
+ }
23
+
24
+
25
+ def _signature(node: ast.FunctionDef | ast.AsyncFunctionDef) -> dict[str, Any]:
26
+ """Parameter names and return annotation only; used for out-parameter evidence."""
27
+ names = [a.arg for a in node.args.posonlyargs + node.args.args]
28
+ decorators = {ast.unparse(d).split(".")[-1] for d in node.decorator_list}
29
+ static = "staticmethod" in decorators or not names or names[0] != "self"
30
+ if names and names[0] in {"self", "cls"}:
31
+ names = names[1:]
32
+ returns = ast.unparse(node.returns) if node.returns is not None else None
33
+ signature = {"parameters": names, "returns": returns}
34
+ # Recorded only when true so instance-method records keep their shape.
35
+ return signature | {"static": True} if static else signature
36
+
37
+
38
+ def _attributes(body: list[ast.stmt]) -> dict[str, str]:
39
+ result = {}
40
+ for node in body:
41
+ if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
42
+ result[node.target.id] = ast.unparse(node.annotation)
43
+ elif isinstance(node, ast.Assign):
44
+ for target in node.targets:
45
+ if isinstance(target, ast.Name):
46
+ result[target.id] = (
47
+ "int"
48
+ if isinstance(node.value, ast.Constant)
49
+ and type(node.value.value) is int
50
+ else "Any"
51
+ )
52
+ return {
53
+ name: annotation
54
+ for name, annotation in result.items()
55
+ if not name.startswith("_")
56
+ }
57
+
58
+
59
+ def _is_enum(node: ast.ClassDef, attributes: dict[str, str]) -> bool:
60
+ bases = {ast.unparse(base).split(".")[-1] for base in node.bases}
61
+ methods = any(
62
+ isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) for n in node.body
63
+ )
64
+ return bool(bases & {"Enum", "IntEnum", "Flag", "IntFlag"}) or (
65
+ not methods
66
+ and any(
67
+ annotation.split(".")[-1] == node.name for annotation in attributes.values()
68
+ )
69
+ )
70
+
71
+
72
+ def _functions(body: list[ast.stmt], *, special_methods: bool = False) -> Surface:
73
+ result: Surface = {
74
+ "methods": set(),
75
+ "properties": set(),
76
+ "getters": set(),
77
+ "constructors": [],
78
+ "signatures": {},
79
+ }
80
+ for node in body:
81
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
82
+ continue
83
+ shape = _shape(node)
84
+ if node.name == "__init__":
85
+ result["constructors"].append(shape)
86
+ elif not node.name.startswith("_") or (
87
+ special_methods and node.name.startswith("__") and node.name.endswith("__")
88
+ ):
89
+ decorators = {ast.unparse(d).split(".")[-1] for d in node.decorator_list}
90
+ if decorators & {"property", "setter", "getter", "deleter"}:
91
+ result["properties"].add(node.name)
92
+ else:
93
+ result["methods"].add(node.name)
94
+ if not any(shape.values()):
95
+ result["getters"].add(node.name)
96
+ result["signatures"].setdefault(node.name, []).append(_signature(node))
97
+ return result
98
+
99
+
100
+ def _class(node: ast.ClassDef) -> Surface:
101
+ result = _functions(node.body, special_methods=True)
102
+ attributes = _attributes(node.body)
103
+ children = {
104
+ n.name: _class(n)
105
+ for n in node.body
106
+ if isinstance(n, ast.ClassDef) and not n.name.startswith("_")
107
+ }
108
+ enums = {
109
+ name: set(child["attributes"])
110
+ for name, child in children.items()
111
+ if child["is_enum"]
112
+ }
113
+ for name, child in children.items():
114
+ enums.update({f"{name}.{key}": value for key, value in child["enums"].items()})
115
+ direct_enums = {name for name in enums if "." not in name}
116
+ enum_members = {
117
+ name
118
+ for name, annotation in attributes.items()
119
+ if annotation.split(".")[-1] in direct_enums | {node.name}
120
+ }
121
+ result.update(
122
+ attributes=attributes,
123
+ bases=[ast.unparse(b) for b in node.bases],
124
+ enums=enums,
125
+ enum_members=enum_members,
126
+ enum_candidates={
127
+ n for n, a in attributes.items() if n[0].isupper() and a in {"Any", "int"}
128
+ },
129
+ opaque_types={n for n, a in attributes.items() if a in {"type", "typing.Type"}},
130
+ nested_classes={n: c for n, c in children.items() if not c["is_enum"]},
131
+ is_enum=_is_enum(node, attributes),
132
+ stub_helper=node.name == "Object"
133
+ and [ast.unparse(b) for b in node.bases] == ["object"]
134
+ and all(isinstance(n, ast.Pass) for n in node.body),
135
+ )
136
+ if result["is_enum"]:
137
+ result["enum_members"].update(attributes)
138
+ return result
139
+
140
+
141
+ def extract(source: str | bytes) -> Surface:
142
+ """Read one module at a time; docstrings and imported helpers are discarded."""
143
+ tree = ast.parse(source)
144
+ classes = {
145
+ node.name: _class(node)
146
+ for node in tree.body
147
+ if isinstance(node, ast.ClassDef) and not node.name.startswith("_")
148
+ }
149
+ members = _functions(tree.body)["methods"] | set(_attributes(tree.body))
150
+ return {"classes": classes, "members": members}
151
+
152
+
153
+ def effective_classes(modules: dict[str, Surface]) -> dict[str, Surface]:
154
+ """Expand declared bases in these modules so flattened native members compare fairly."""
155
+ declared = {
156
+ f"{module}.{name}": cls
157
+ for module, data in modules.items()
158
+ for name, cls in data["classes"].items()
159
+ }
160
+ resolved: dict[str, Surface] = {}
161
+
162
+ def resolve(key: str, active: tuple[str, ...] = ()) -> Surface:
163
+ if key in active:
164
+ raise ValueError(f"Cyclic stub inheritance: {key}")
165
+ if key in resolved:
166
+ return resolved[key]
167
+ cls = declared[key]
168
+ merged = {
169
+ k: v.copy() if isinstance(v, (dict, set, list)) else v
170
+ for k, v in cls.items()
171
+ }
172
+ for base in reversed(cls["bases"]):
173
+ base = base.removeprefix("PySide2.").removeprefix("PythonQt.")
174
+ base = base if "." in base else key.rpartition(".")[0] + "." + base
175
+ if base in declared:
176
+ parent = resolve(base, (*active, key))
177
+ for field in (
178
+ "methods",
179
+ "properties",
180
+ "getters",
181
+ "enum_members",
182
+ "enum_candidates",
183
+ "opaque_types",
184
+ ):
185
+ merged[field] |= parent[field]
186
+ for field in ("attributes", "enums", "nested_classes", "signatures"):
187
+ merged[field] = parent[field] | merged[field]
188
+ resolved[key] = merged
189
+ return merged
190
+
191
+ return {key: resolve(key) for key in declared}