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

Method py_new

crates/vm/src/builtins/complex.rs:204–262  ·  view source on GitHub ↗
(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine)

Source from the content-addressed store, hash-verified

202 }
203
204 fn py_new(_cls: &Py<PyType>, args: Self::Args, vm: &VirtualMachine) -> PyResult<Self> {
205 let imag_missing = args.imag.is_missing();
206 let (real, real_was_complex) = match args.real {
207 OptionalArg::Missing => (Complex64::new(0.0, 0.0), false),
208 OptionalArg::Present(val) => {
209 if let Some(c) = val.try_complex(vm)? {
210 c
211 } else if let Some(s) = val.downcast_ref::<PyStr>() {
212 if args.imag.is_present() {
213 return Err(vm.new_type_error(
214 "complex() can't take second arg if first is a string",
215 ));
216 }
217 let (re, im) = s
218 .to_str()
219 .and_then(rustpython_literal::complex::parse_str)
220 .ok_or_else(|| vm.new_value_error("complex() arg is a malformed string"))?;
221 return Ok(Self::from(Complex64 { re, im }));
222 } else {
223 return Err(vm.new_type_error(format!(
224 "complex() first argument must be a string or a number, not '{}'",
225 val.class().name()
226 )));
227 }
228 }
229 };
230
231 let (imag, imag_was_complex) = match args.imag {
232 // Copy the imaginary from the real to the real of the imaginary
233 // if an imaginary argument is not passed in
234 OptionalArg::Missing => (Complex64::new(real.im, 0.0), false),
235 OptionalArg::Present(obj) => {
236 if let Some(c) = obj.try_complex(vm)? {
237 c
238 } else if obj.class().fast_issubclass(vm.ctx.types.str_type) {
239 return Err(vm.new_type_error("complex() second arg can't be a string"));
240 } else {
241 return Err(vm.new_type_error(format!(
242 "complex() second argument must be a number, not '{}'",
243 obj.class().name()
244 )));
245 }
246 }
247 };
248
249 let final_real = if imag_was_complex {
250 real.re - imag.im
251 } else {
252 real.re
253 };
254
255 let final_imag = if real_was_complex && !imag_missing {
256 imag.re + real.im
257 } else {
258 imag.re
259 };
260 let value = Complex64::new(final_real, final_imag);
261 Ok(Self::from(value))

Callers

nothing calls this directly

Calls 7

newFunction · 0.85
try_complexMethod · 0.80
ok_or_elseMethod · 0.80
to_strMethod · 0.80
fast_issubclassMethod · 0.80
ErrClass · 0.50
classMethod · 0.45

Tested by

no test coverage detected