PyObject_Format
(&self, obj: &PyObject, format_spec: PyStrRef)
| 549 | |
| 550 | // PyObject_Format |
| 551 | pub fn format(&self, obj: &PyObject, format_spec: PyStrRef) -> PyResult<PyStrRef> { |
| 552 | if format_spec.is_empty() { |
| 553 | let obj = match obj.to_owned().downcast_exact::<PyStr>(self) { |
| 554 | Ok(s) => return Ok(s.into_pyref()), |
| 555 | Err(obj) => obj, |
| 556 | }; |
| 557 | if obj.class().is(self.ctx.types.int_type) { |
| 558 | return obj.str(self); |
| 559 | } |
| 560 | } |
| 561 | let bound_format = self |
| 562 | .get_special_method(obj, identifier!(self, __format__))? |
| 563 | .ok_or_else(|| { |
| 564 | self.new_type_error(format!( |
| 565 | "Type {} doesn't define __format__", |
| 566 | obj.class().name() |
| 567 | )) |
| 568 | })?; |
| 569 | let formatted = bound_format.invoke((format_spec,), self)?; |
| 570 | formatted.downcast().map_err(|result| { |
| 571 | self.new_type_error(format!( |
| 572 | "__format__ must return a str, not {}", |
| 573 | &result.class().name() |
| 574 | )) |
| 575 | }) |
| 576 | } |
| 577 | pub fn format_utf8(&self, obj: &PyObject, format_spec: PyStrRef) -> PyResult<PyRef<PyUtf8Str>> { |
| 578 | self.format(obj, format_spec)?.try_into_utf8(self) |
| 579 | } |
no test coverage detected