MCPcopy Index your code
hub / github.com/RustPython/RustPython / try_complex

Method try_complex

crates/vm/src/builtins/complex.rs:89–129  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

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
132pub fn init(context: &'static Context) {

Callers 4

try_from_objectMethod · 0.80
ast_from_objectMethod · 0.80
py_newMethod · 0.80
from_numberMethod · 0.80

Calls 11

newFunction · 0.85
try_float_optMethod · 0.80
to_f64Method · 0.80
SomeClass · 0.50
warnFunction · 0.50
ErrClass · 0.50
get_methodMethod · 0.45
cloneMethod · 0.45
callMethod · 0.45
to_ownedMethod · 0.45
classMethod · 0.45

Tested by

no test coverage detected