Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions newsfragments/6607.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
srub: do not emit `__str__` and `__repr__` methods with the same signature as their `object` counterpart in the generated stubs
50 changes: 47 additions & 3 deletions pyo3-introspection/src/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ fn is_type_check_only(class: &Class) -> bool {
}

fn class_stubs(class: &Class, imports: &Imports) -> String {
let methods = emitted_methods(class).collect::<Vec<_>>();
let mut buffer = String::new();
for decorator in &class.decorators {
buffer.push('@');
Expand All @@ -209,7 +210,7 @@ fn class_stubs(class: &Class, imports: &Imports) -> String {
}
buffer.push(':');
if class.docstring.is_none()
&& class.methods.is_empty()
&& methods.is_empty()
&& class.attributes.is_empty()
&& class.inner_classes.is_empty()
{
Expand All @@ -223,7 +224,7 @@ fn class_stubs(class: &Class, imports: &Imports) -> String {
buffer.push_str("\n ");
push_indented(&mut buffer, " ", &attribute_stubs(attribute, imports));
}
for method in &class.methods {
for method in methods {
// We do the indentation
buffer.push_str("\n ");
push_indented(
Expand All @@ -240,6 +241,49 @@ fn class_stubs(class: &Class, imports: &Imports) -> String {
buffer
}

/// The methods to write in the class stub
fn emitted_methods(class: &Class) -> impl Iterator<Item = &Function> {
class
.methods
.iter()
.filter(|method| !is_redundant_object_method(method))
}

/// `__str__` and `__repr__` with the exact same signature as their `object` counterpart are
/// inherited from `object` by every class, so declaring them again is redundant (ruff `PYI029`).
///
/// Methods with a docstring are kept to not lose documentation.
fn is_redundant_object_method(method: &Function) -> bool {
let Arguments {
positional_only_arguments,
arguments,
vararg,
keyword_only_arguments,
kwarg,
} = &method.arguments;
matches!(method.name.as_str(), "__str__" | "__repr__")
&& method.decorators.is_empty()
&& !method.is_async
&& method.docstring.is_none()
&& matches!(
positional_only_arguments.as_slice(),
[Argument {
annotation: None,
default_value: None,
..
}]
)
&& arguments.is_empty()
&& vararg.is_none()
&& keyword_only_arguments.is_empty()
&& kwarg.is_none()
&& matches!(
&method.returns,
Some(Expr::Attribute { value, attr })
if attr == "str" && matches!(&**value, Expr::Name { id } if id == "builtins")
)
}

fn function_stubs(function: &Function, imports: &Imports, class_name: Option<&str>) -> String {
// Signature
let mut parameters = Vec::new();
Expand Down Expand Up @@ -687,7 +731,7 @@ impl ReferencedNames {
for decorator in &class.decorators {
self.walk_expr(decorator);
}
for method in &class.methods {
for method in emitted_methods(class) {
self.walk_function(method);
}
for attr in &class.attributes {
Expand Down
1 change: 0 additions & 1 deletion pytests/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ requires-python = ">=3.9"
"stubs/*.pyi" = [
"I001", # unsorted imports
"PYI020", # quoted annotations
"PYI029", # redundant `__str__` definition
"UP037", # quoted annotations
]

Expand Down
1 change: 0 additions & 1 deletion pytests/stubs/comparisons.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,6 @@ class OrderedDerived:
def __lt__(self, value: object, /) -> bool: ...
def __ne__(self, value: object, /) -> bool: ...
def __new__(cls, /, value: SupportsIndex) -> Self: ...
def __str__(self, /) -> str: ...

@final
class OrderedRichCmp:
Expand Down
2 changes: 0 additions & 2 deletions pytests/stubs/enums.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -100,14 +100,12 @@ class SimpleEnum:
def __eq__(self, value: object, /) -> bool: ...
def __int__(self, /) -> int: ...
def __ne__(self, value: object, /) -> bool: ...
def __repr__(self, /) -> str: ...

@final
class SimpleEnumWithoutDerive:
A: Final[SimpleEnumWithoutDerive]
B: Final[SimpleEnumWithoutDerive]
def __int__(self, /) -> int: ...
def __repr__(self, /) -> str: ...

@disjoint_base
class SimpleTupleEnum:
Expand Down
2 changes: 0 additions & 2 deletions pytests/stubs/pyclasses.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ class Number:
def __or__(self, other: object, /) -> Number: ...
def __pos__(self, /) -> Number: ...
def __pow__(self, other: object, modulo: object = None, /) -> Number: ...
def __repr__(self, /) -> str: ...
def __rshift__(self, other: object, /) -> Number: ...
def __str__(self, /) -> str: ...
def __sub__(self, other: object, /) -> Number: ...
def __truediv__(self, other: object, /) -> Number: ...
def __xor__(self, other: object, /) -> Number: ...
Expand Down
3 changes: 0 additions & 3 deletions pytests/stubs/subclassing.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@ __all__ = ["SubDict", "Subclass", "Subclassable"]
@final
class SubDict(dict):
def __new__(cls, /) -> Self: ...
def __str__(self, /) -> str: ...

@final
class Subclass(Subclassable):
def __new__(cls, /) -> Self: ...
def __str__(self, /) -> str: ...

@disjoint_base
class Subclassable:
def __new__(cls, /) -> Self: ...
def __str__(self, /) -> str: ...