Tries converting a python object into a complex, returns an option of whether the complex and whether the object was a complex originally or coerced into one
(&self, vm: &VirtualMachine)
| 87 | /// Tries converting a python object into a complex, returns an option of whether the complex |
| 88 | /// and whether the object was a complex originally or coerced into one |
| 89 | pub fn try_complex(&self, vm: &VirtualMachine) -> PyResult<Option<(Complex64, bool)>> { |
| 90 | if let Some(complex) = self.downcast_ref_if_exact::<PyComplex>(vm) { |
| 91 | return Ok(Some((complex.value, true))); |
| 92 | } |
| 93 | if let Some(method) = vm.get_method(self.clone(), identifier!(vm, __complex__)) { |
| 94 | let result = method?.call((), vm)?; |
| 95 | |
| 96 | let ret_class = result.class().to_owned(); |
| 97 | if let Some(ret) = result.downcast_ref::<PyComplex>() { |
| 98 | _warnings::warn( |
| 99 | vm.ctx.exceptions.deprecation_warning, |
| 100 | format!( |
| 101 | "__complex__ returned non-complex (type {ret_class}). \ |
| 102 | The ability to return an instance of a strict subclass of complex \ |
| 103 | is deprecated, and may be removed in a future version of Python." |
| 104 | ), |
| 105 | 1, |
| 106 | vm, |
| 107 | )?; |
| 108 | |
| 109 | return Ok(Some((ret.value, true))); |
| 110 | } else { |
| 111 | return match result.downcast_ref::<PyComplex>() { |
| 112 | Some(complex_obj) => Ok(Some((complex_obj.value, true))), |
| 113 | None => Err(vm.new_type_error(format!( |
| 114 | "__complex__ returned non-complex (type '{}')", |
| 115 | result.class().name() |
| 116 | ))), |
| 117 | }; |
| 118 | } |
| 119 | } |
| 120 | // `complex` does not have a `__complex__` by default, so subclasses might not either, |
| 121 | // use the actual stored value in this case |
| 122 | if let Some(complex) = self.downcast_ref::<PyComplex>() { |
| 123 | return Ok(Some((complex.value, true))); |
| 124 | } |
| 125 | if let Some(float) = self.try_float_opt(vm) { |
| 126 | return Ok(Some((Complex64::new(float?.to_f64(), 0.0), false))); |
| 127 | } |
| 128 | Ok(None) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub fn init(context: &'static Context) { |
no test coverage detected