@@ -152,22 +152,25 @@ impl Constructor for PyComplex {
152152 type Args = ComplexArgs ;
153153
154154 fn slot_new ( cls : PyTypeRef , func_args : FuncArgs , vm : & VirtualMachine ) -> PyResult {
155+ // Optimization: return exact complex as-is (only when imag is not provided)
156+ if cls. is ( vm. ctx . types . complex_type )
157+ && func_args. args . len ( ) == 1
158+ && func_args. kwargs . is_empty ( )
159+ && func_args. args [ 0 ] . class ( ) . is ( vm. ctx . types . complex_type )
160+ {
161+ return Ok ( func_args. args [ 0 ] . clone ( ) ) ;
162+ }
163+
155164 let args: Self :: Args = func_args. bind ( vm) ?;
165+ let payload = Self :: py_new ( & cls, args, vm) ?;
166+ payload. into_ref_with_type ( vm, cls) . map ( Into :: into)
167+ }
168+
169+ fn py_new ( _cls : & Py < PyType > , args : Self :: Args , vm : & VirtualMachine ) -> PyResult < Self > {
156170 let imag_missing = args. imag . is_missing ( ) ;
157171 let ( real, real_was_complex) = match args. real {
158172 OptionalArg :: Missing => ( Complex64 :: new ( 0.0 , 0.0 ) , false ) ,
159173 OptionalArg :: Present ( val) => {
160- let val = if cls. is ( vm. ctx . types . complex_type ) && imag_missing {
161- match val. downcast_exact :: < Self > ( vm) {
162- Ok ( c) => {
163- return Ok ( c. into_pyref ( ) . into ( ) ) ;
164- }
165- Err ( val) => val,
166- }
167- } else {
168- val
169- } ;
170-
171174 if let Some ( c) = val. try_complex ( vm) ? {
172175 c
173176 } else if let Some ( s) = val. downcast_ref :: < PyStr > ( ) {
@@ -180,9 +183,7 @@ impl Constructor for PyComplex {
180183 . to_str ( )
181184 . and_then ( rustpython_literal:: complex:: parse_str)
182185 . ok_or_else ( || vm. new_value_error ( "complex() arg is a malformed string" ) ) ?;
183- return Self :: from ( Complex64 { re, im } )
184- . into_ref_with_type ( vm, cls)
185- . map ( Into :: into) ;
186+ return Ok ( Self :: from ( Complex64 { re, im } ) ) ;
186187 } else {
187188 return Err ( vm. new_type_error ( format ! (
188189 "complex() first argument must be a string or a number, not '{}'" ,
@@ -222,13 +223,7 @@ impl Constructor for PyComplex {
222223 imag. re
223224 } ;
224225 let value = Complex64 :: new ( final_real, final_imag) ;
225- Self :: from ( value)
226- . into_ref_with_type ( vm, cls)
227- . map ( Into :: into)
228- }
229-
230- fn py_new ( _cls : & Py < PyType > , _args : Self :: Args , _vm : & VirtualMachine ) -> PyResult < Self > {
231- unreachable ! ( "use slot_new" )
226+ Ok ( Self :: from ( value) )
232227 }
233228}
234229
0 commit comments