Skip to content

Commit 892dd81

Browse files
feat(stubgen): allow __suffix__ and __prefix__ for classes (#1235)
It is currently not possible to *add* functions to a class using patterns. This may be necessary if functions are added to a class through mechanisms other than nanobind. This PR adds the possibility to match on `__suffix__` and `__prefix__` within a class, like it is possible to do within modules already, which can be used to add anything to the beginning or end of a class using patterns. Signed-off-by: Ingo Müller <[email protected]>
1 parent 68b9ae8 commit 892dd81

File tree

4 files changed

+15
-3
lines changed

4 files changed

+15
-3
lines changed

docs/typing.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -714,6 +714,6 @@ you may use the special ``\from`` escape code to import them:
714714
def lookup(array: Array[T], index: Literal[0] = 0) -> _Opt[T]:
715715
\doc
716716
717-
You may also add free-form text the beginning or the end of the generated stub.
718-
To do so, add an entry that matches on ``module_name.__prefix__`` or
719-
``module_name.__suffix__``.
717+
You may also add free-form text the beginning or the end of the generated stub
718+
module or of a class. To do so, add an entry that matches on ``name.__prefix__``
719+
or ``name.__suffix__`` where ``name`` is the name of the module or class.

src/stubgen.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -567,8 +567,10 @@ def put_type(self, tp: NbType, name: Optional[str]):
567567
self.put_docstr(docstr)
568568
if len(tp_dict):
569569
self.write("\n")
570+
self.apply_pattern(self.prefix + ".__prefix__", None)
570571
for k, v in tp_dict.items():
571572
self.put(v, k, tp)
573+
self.apply_pattern(self.prefix + ".__suffix__", None)
572574
if output_len == len(self.output):
573575
self.write_ln("pass\n")
574576
self.depth -= 1

tests/pattern_file.nb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,9 @@ test_typing_ext.__prefix__:
1717

1818
test_typing_ext.__suffix__:
1919
# a suffix
20+
21+
test_typing_ext.Foo.__prefix__:
22+
# a class prefix
23+
24+
test_typing_ext.Foo.__suffix__:
25+
# a class suffix

tests/test_typing_ext.pyi.ref

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ from .submodule import F as F, f as f2
99
# a prefix
1010

1111
class Foo:
12+
# a class prefix
13+
1214
def __lt__(self, arg: int, /) -> bool: ...
1315

1416
def __gt__(self, arg: int, /) -> bool: ...
@@ -19,6 +21,8 @@ class Foo:
1921

2022
lt_alias = __lt__
2123

24+
# a class suffix
25+
2226
def f() -> None: ...
2327

2428
def makeNestedClass() -> py_stub_test.AClass.NestedClass: ...

0 commit comments

Comments
 (0)