-
If there is a rust struct like below, use pyo3::{exceptions::PyValueError, prelude::*, types::PyDict};
#[pyclass(subclass)]
pub struct Animal {}
#[pymethods]
impl Animal {
#[new]
pub fn new() -> PyResult<Self> {
Err(PyValueError::new_err("not_implemented"))
}
/// Configure with given config.
pub fn configure(&mut self, valid_config: &Bound<'_, PyDict>) -> PyResult<()> {
Err(PyValueError::new_err("not_implemented"))
}
pub fn run(&self) -> PyResult<()> {
Err(PyValueError::new_err("not_implemented"))
}
}
#[pymodule]
mod ex {
#[pymodule_export]
use super::Animal;
} and then at python, inherit like below, import ex
from ex import Animal
class Dog(Animal):
def __new__(cls):
return cls
def configure(self, valid_config):
self.cfg = valid_config
def run(self):
print(repr(self.cfg)) This (use as class method) works. ( output : {'name': 'foo bar'} ) config = dict({"name": "foo bar"})
dog = Dog()
Dog.configure(dog, config)
Dog.run(dog) But if i use this as a instance method, like config = dict({"name": "foo bar"})
dog = Dog()
dog.configure(config)
dog.run() The Error Occurs.
Is there are solution for solve this? I want to use instance method ps: this works too. dog = Dog()
dog.configure(dog, config)
dog.run(dog) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The problem here is your >>> type(Dog())
type # should be "Dog" So your class A:
...
class Dog:
def configure(self, valid_config):
self.cfg = valid_config
>>> a = A()
>>> Dog.configure(a, {})
>>> a.cfg
{} This pure Python example works without problem (but pretty cursed I guess) |
Beta Was this translation helpful? Give feedback.
The problem here is your
Dog.__new__
implementation. It is supposed to return a new instance of the class, but you are returning the class object itself:So your
dog
is not an instance ofDog
(but oftype
), that's why the instance syntax is not working. I believe the class method syntax works here, because it does not validate whatself
is. It could be any unrelated type for that matter:This pure Python example works without problem (but pretty cursed I guess)