@@ -161,33 +161,34 @@ impl GILGuard {
161161 // extension-module feature is not activated - extension modules don't care about
162162 // auto-initialize so this avoids breaking existing builds.
163163 // - Otherwise, just check the GIL is initialized.
164- cfg_if:: cfg_if! {
165- if #[ cfg( all( feature = "auto-initialize" , not( any( PyPy , GraalPy ) ) ) ) ] {
164+ #[ cfg( all( feature = "auto-initialize" , not( any( PyPy , GraalPy ) ) ) ) ]
165+ {
166+ prepare_freethreaded_python ( ) ;
167+ }
168+ #[ cfg( not( all( feature = "auto-initialize" , not( any( PyPy , GraalPy ) ) ) ) ) ]
169+ {
170+ // This is a "hack" to make running `cargo test` for PyO3 convenient (i.e. no need
171+ // to specify `--features auto-initialize` manually. Tests within the crate itself
172+ // all depend on the auto-initialize feature for conciseness but Cargo does not
173+ // provide a mechanism to specify required features for tests.
174+ #[ cfg( not( any( PyPy , GraalPy ) ) ) ]
175+ if option_env ! ( "CARGO_PRIMARY_PACKAGE" ) . is_some ( ) {
166176 prepare_freethreaded_python ( ) ;
167- } else {
168- // This is a "hack" to make running `cargo test` for PyO3 convenient (i.e. no need
169- // to specify `--features auto-initialize` manually. Tests within the crate itself
170- // all depend on the auto-initialize feature for conciseness but Cargo does not
171- // provide a mechanism to specify required features for tests.
172- #[ cfg( not( any( PyPy , GraalPy ) ) ) ]
173- if option_env!( "CARGO_PRIMARY_PACKAGE" ) . is_some( ) {
174- prepare_freethreaded_python( ) ;
175- }
176-
177- START . call_once_force( |_| unsafe {
178- // Use call_once_force because if there is a panic because the interpreter is
179- // not initialized, it's fine for the user to initialize the interpreter and
180- // retry.
181- assert_ne!(
182- ffi:: Py_IsInitialized ( ) ,
183- 0 ,
184- "The Python interpreter is not initialized and the `auto-initialize` \
177+ }
178+
179+ START . call_once_force ( |_| unsafe {
180+ // Use call_once_force because if there is a panic because the interpreter is
181+ // not initialized, it's fine for the user to initialize the interpreter and
182+ // retry.
183+ assert_ne ! (
184+ ffi:: Py_IsInitialized ( ) ,
185+ 0 ,
186+ "The Python interpreter is not initialized and the `auto-initialize` \
185187 feature is not enabled.\n \n \
186188 Consider calling `pyo3::prepare_freethreaded_python()` before attempting \
187189 to use Python APIs."
188- ) ;
189- } ) ;
190- }
190+ ) ;
191+ } ) ;
191192 }
192193
193194 // SAFETY: We have ensured the Python interpreter is initialized.
0 commit comments