Skip to content
Merged
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/5552.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Introspection: `@typing.final` on final classes
51 changes: 35 additions & 16 deletions pyo3-introspection/src/introspection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,17 @@ fn convert_members<'a>(
chunks_by_parent,
)?);
}
Chunk::Class { name, id } => {
classes.push(convert_class(id, name, chunks_by_id, chunks_by_parent)?)
}
Chunk::Class {
name,
id,
decorators,
} => classes.push(convert_class(
id,
name,
decorators,
chunks_by_id,
chunks_by_parent,
)?),
Chunk::Function {
name,
id: _,
Expand Down Expand Up @@ -178,6 +186,7 @@ fn convert_members<'a>(
fn convert_class(
id: &str,
name: &str,
decorators: &[ChunkTypeHint],
chunks_by_id: &HashMap<&str, &Chunk>,
chunks_by_parent: &HashMap<&str, Vec<&Chunk>>,
) -> Result<Class> {
Expand All @@ -198,9 +207,29 @@ fn convert_class(
name: name.into(),
methods,
attributes,
decorators: decorators
.iter()
.map(convert_decorator)
.collect::<Result<_>>()?,
})
}

fn convert_decorator(decorator: &ChunkTypeHint) -> Result<PythonIdentifier> {
match convert_type_hint(decorator) {
TypeHint::Plain(id) => Ok(PythonIdentifier {
module: None,
name: id.clone(),
}),
TypeHint::Ast(expr) => {
if let TypeHintExpr::Identifier(i) = expr {
Ok(i)
} else {
bail!("PyO3 introspection currently only support decorators that are identifiers of a Python function")
}
}
}
}

fn convert_function(
name: &str,
arguments: &ChunkArguments,
Expand All @@ -211,19 +240,7 @@ fn convert_function(
name: name.into(),
decorators: decorators
.iter()
.map(|d| match convert_type_hint(d) {
TypeHint::Plain(id) => Ok(PythonIdentifier {
module: None,
name: id.clone(),
}),
TypeHint::Ast(expr) => {
if let TypeHintExpr::Identifier(i) = expr {
Ok(i)
} else {
bail!("A decorator must be the identifier of a Python function")
}
}
})
.map(convert_decorator)
.collect::<Result<_>>()?,
arguments: Arguments {
positional_only_arguments: arguments.posonlyargs.iter().map(convert_argument).collect(),
Expand Down Expand Up @@ -444,6 +461,8 @@ enum Chunk {
Class {
id: String,
name: String,
#[serde(default)]
decorators: Vec<ChunkTypeHint>,
},
Function {
#[serde(default)]
Expand Down
2 changes: 2 additions & 0 deletions pyo3-introspection/src/model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pub struct Class {
pub name: String,
pub methods: Vec<Function>,
pub attributes: Vec<Attribute>,
/// decorator like 'typing.final'
pub decorators: Vec<PythonIdentifier>,
}

#[derive(Debug, Eq, PartialEq, Clone, Hash)]
Expand Down
18 changes: 17 additions & 1 deletion pyo3-introspection/src/stubs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,15 @@ fn module_stubs(module: &Module, parents: &[&str]) -> String {
}

fn class_stubs(class: &Class, imports: &Imports) -> String {
let mut buffer = format!("class {}:", class.name);
let mut buffer = String::new();
for decorator in &class.decorators {
buffer.push('@');
imports.serialize_identifier(decorator, &mut buffer);
buffer.push('\n');
}
buffer.push_str("class ");
buffer.push_str(&class.name);
buffer.push(':');
if class.methods.is_empty() && class.attributes.is_empty() {
buffer.push_str(" ...");
return buffer;
Expand Down Expand Up @@ -433,6 +441,9 @@ impl ElementsUsedInAnnotations {
}

fn walk_class(&mut self, class: &Class) {
for decorator in &class.decorators {
self.walk_identifier(decorator);
}
for method in &class.methods {
self.walk_function(method);
}
Expand Down Expand Up @@ -658,6 +669,10 @@ mod tests {
name: "A".into(),
methods: Vec::new(),
attributes: Vec::new(),
decorators: vec![PythonIdentifier {
module: Some("typing".into()),
name: "final".into(),
}],
}],
functions: vec![Function {
name: String::new(),
Expand All @@ -683,6 +698,7 @@ mod tests {
"from bat import A as A2",
"from builtins import int as int2",
"from foo import A as A3, B",
"from typing import final"
]
);
let mut output = String::new();
Expand Down
31 changes: 19 additions & 12 deletions pyo3-macros-backend/src/introspection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,26 @@ pub fn class_introspection_code(
pyo3_crate_path: &PyO3CratePath,
ident: &Ident,
name: &str,
is_final: bool,
) -> TokenStream {
IntrospectionNode::Map(
[
("type", IntrospectionNode::String("class".into())),
(
"id",
IntrospectionNode::IntrospectionId(Some(ident_to_type(ident))),
),
("name", IntrospectionNode::String(name.into())),
]
.into(),
)
.emit(pyo3_crate_path)
let mut desc = HashMap::from([
("type", IntrospectionNode::String("class".into())),
(
"id",
IntrospectionNode::IntrospectionId(Some(ident_to_type(ident))),
),
("name", IntrospectionNode::String(name.into())),
]);
if is_final {
desc.insert(
"decorators",
IntrospectionNode::List(vec![IntrospectionNode::ConstantType(
PythonIdentifier::module_attr("typing", "final"),
)
.into()]),
);
}
IntrospectionNode::Map(desc).emit(pyo3_crate_path)
}

#[expect(clippy::too_many_arguments)]
Expand Down
7 changes: 6 additions & 1 deletion pyo3-macros-backend/src/pyclass.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2683,7 +2683,12 @@ impl<'a> PyClassImplsBuilder<'a> {
let Ctx { pyo3_path, .. } = ctx;
let name = get_class_python_name(self.cls, self.attr).to_string();
let ident = self.cls;
let static_introspection = class_introspection_code(pyo3_path, ident, &name);
let static_introspection = class_introspection_code(
pyo3_path,
ident,
&name,
self.attr.options.subclass.is_none(),
);
let introspection_id = introspection_id_const();
quote! {
#static_introspection
Expand Down
3 changes: 1 addition & 2 deletions pytests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ mod pyo3_pytests {
#[pymodule_export]
use {
comparisons::comparisons, consts::consts, enums::enums, pyclasses::pyclasses,
pyfunctions::pyfunctions,
pyfunctions::pyfunctions, subclassing::subclassing,
};

// Inserting to sys.modules allows importing submodules nicely from Python
Expand All @@ -43,7 +43,6 @@ mod pyo3_pytests {
m.add_wrapped(wrap_pymodule!(othermod::othermod))?;
m.add_wrapped(wrap_pymodule!(path::path))?;
m.add_wrapped(wrap_pymodule!(sequence::sequence))?;
m.add_wrapped(wrap_pymodule!(subclassing::subclassing))?;

// Inserting to sys.modules allows importing submodules nicely from Python
// e.g. import pyo3_pytests.buf_and_str as bas
Expand Down
31 changes: 15 additions & 16 deletions pytests/src/subclassing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,22 @@

use pyo3::prelude::*;

#[pyclass(subclass)]
pub struct Subclassable {}
#[pymodule(gil_used = false)]
pub mod subclassing {
use pyo3::prelude::*;

#[pymethods]
impl Subclassable {
#[new]
fn new() -> Self {
Subclassable {}
}
#[pyclass(subclass)]
pub struct Subclassable {}

fn __str__(&self) -> &'static str {
"Subclassable"
}
}
#[pymethods]
impl Subclassable {
#[new]
fn new() -> Self {
Subclassable {}
}

#[pymodule]
pub fn subclassing(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_class::<Subclassable>()?;
Ok(())
fn __str__(&self) -> &'static str {
"Subclassable"
}
}
}
9 changes: 9 additions & 0 deletions pytests/stubs/comparisons.pyi
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
from typing import final

@final
class Eq:
def __eq__(self, /, other: Eq) -> bool: ...
def __ne__(self, /, other: Eq) -> bool: ...
def __new__(cls, /, value: int) -> Eq: ...

@final
class EqDefaultNe:
def __eq__(self, /, other: EqDefaultNe) -> bool: ...
def __new__(cls, /, value: int) -> EqDefaultNe: ...

@final
class EqDerived:
def __eq__(self, /, other: EqDerived) -> bool: ...
def __ne__(self, /, other: EqDerived) -> bool: ...
def __new__(cls, /, value: int) -> EqDerived: ...

@final
class Ordered:
def __eq__(self, /, other: Ordered) -> bool: ...
def __ge__(self, /, other: Ordered) -> bool: ...
Expand All @@ -21,6 +27,7 @@ class Ordered:
def __ne__(self, /, other: Ordered) -> bool: ...
def __new__(cls, /, value: int) -> Ordered: ...

@final
class OrderedDefaultNe:
def __eq__(self, /, other: OrderedDefaultNe) -> bool: ...
def __ge__(self, /, other: OrderedDefaultNe) -> bool: ...
Expand All @@ -29,6 +36,7 @@ class OrderedDefaultNe:
def __lt__(self, /, other: OrderedDefaultNe) -> bool: ...
def __new__(cls, /, value: int) -> OrderedDefaultNe: ...

@final
class OrderedDerived:
def __eq__(self, /, other: OrderedDerived) -> bool: ...
def __ge__(self, /, other: OrderedDerived) -> bool: ...
Expand All @@ -40,6 +48,7 @@ class OrderedDerived:
def __new__(cls, /, value: int) -> OrderedDerived: ...
def __str__(self, /) -> str: ...

@final
class OrderedRichCmp:
def __eq__(self, /, other: OrderedRichCmp) -> bool: ...
def __ge__(self, /, other: OrderedRichCmp) -> bool: ...
Expand Down
3 changes: 2 additions & 1 deletion pytests/stubs/consts.pyi
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import Final
from typing import Final, final

PI: Final[float]
SIMPLE: Final = "SIMPLE"

@final
class ClassWithConst:
INSTANCE: Final[ClassWithConst]
3 changes: 3 additions & 0 deletions pytests/stubs/enums.pyi
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from typing import final

class ComplexEnum: ...
class MixedComplexEnum: ...

@final
class SimpleEnum:
def __eq__(self, /, other: SimpleEnum | int) -> bool: ...
def __ne__(self, /, other: SimpleEnum | int) -> bool: ...
Expand Down
9 changes: 8 additions & 1 deletion pytests/stubs/pyclasses.pyi
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from _typeshed import Incomplete
from typing import Any
from typing import Any, final

class AssertingBaseClass:
def __new__(cls, /, expected_type: Any) -> AssertingBaseClass: ...

@final
class ClassWithDecorators:
def __new__(cls, /) -> ClassWithDecorators: ...
@property
Expand All @@ -18,16 +19,20 @@ class ClassWithDecorators:
@staticmethod
def static_method() -> int: ...

@final
class ClassWithDict:
def __new__(cls, /) -> ClassWithDict: ...

@final
class ClassWithoutConstructor: ...

@final
class EmptyClass:
def __len__(self, /) -> int: ...
def __new__(cls, /) -> EmptyClass: ...
def method(self, /) -> None: ...

@final
class PlainObject:
@property
def bar(self, /) -> int: ...
Expand All @@ -38,10 +43,12 @@ class PlainObject:
@foo.setter
def foo(self, /, value: str) -> None: ...

@final
class PyClassIter:
def __new__(cls, /) -> PyClassIter: ...
def __next__(self, /) -> int: ...

@final
class PyClassThreadIter:
def __new__(cls, /) -> PyClassThreadIter: ...
def __next__(self, /) -> int: ...
Expand Down
3 changes: 3 additions & 0 deletions pytests/stubs/subclassing.pyi
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
class Subclassable:
def __new__(cls, /) -> Subclassable: ...
def __str__(self, /) -> str: ...
Loading