Skip to content

core: prevent implicit bool conversion in ScriptInterface#5246

Open
adr1ja wants to merge 6 commits intoespressomd:pythonfrom
adr1ja:fix/script-interface-type-safety
Open

core: prevent implicit bool conversion in ScriptInterface#5246
adr1ja wants to merge 6 commits intoespressomd:pythonfrom
adr1ja:fix/script-interface-type-safety

Conversation

@adr1ja
Copy link
Contributor

@adr1ja adr1ja commented Feb 3, 2026

Fixes ##5036

Description of changes:

This PR addresses issue #5036 by enforcing strict type checking for boolean values within the ScriptInterface framework. I modified the allow_conversion template trait in src/script_interface/get_value.hpp to explicitly exclude bool from implicit conversions to arithmetic types (integers and floating-point numbers). This ensures that boolean arguments passed from the Python interface are no longer silently cast to 0 or 1 in the C++ core, preventing potential silent physics bugs.

Also, verified the fix with a runtime check:
./pypresso -c "import espressomd; s=espressomd.System(box_l=[1,1,1]); s.part.by_id(True)"

image

The system now correctly raises a RuntimeError: Provided argument of type 'bool' for parameter 'p_id' is not convertible to 'int'.

@adr1ja
Copy link
Contributor Author

adr1ja commented Feb 3, 2026

Hi @jngrad, the C++ fix is verified and the style/formatting issues are now resolved (the CI style check is green).

However, the build stage is failing because this change is enforcing strict type safety on existing tests and tutorials that were relying on implicit bool-to-int conversions. For example, I see failures in the default and tutorials-samples jobs.

Since this is a breaking change for the current test suite, how would you like me to proceed? Should I attempt to fix the offending tests?

@jngrad
Copy link
Member

jngrad commented Feb 4, 2026

I think you should identify and report here which parts of the code rely on implicit bool-to-int conversions. I suspect you will need to use GDB to find out some of the culprits. Bear in mind that implicit bool-to-int conversion is the Pythonic behavior, so there might be legitimate reasons for features to leverage that behavior. This ticket is about making the ESPResSo behavior diverge from the Python behavior, so we need to be able to justify why we are making this change. Here are instructions on how to use GDB with ESPResSo (you won't need MPI) and how to run checkpoint tests.

For more context: cannot subclass from bool type, which also explains why isinstance(np.True_, bool) evaluates to False and one has to use isinstance(x, (bool, np.bool_)) to check if a value is a boolean type (NumPy types docs), and why Cython created the special bint type (Cython types docs).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants