project-gemmi / gemmi

macromolecular crystallography library and utilities
https://project-gemmi.github.io/
Mozilla Public License 2.0
220 stars 44 forks source link

Add Custom Boolean Check for Model Objects #319

Closed Dialpuri closed 3 months ago

Dialpuri commented 3 months ago

Description

This PR adds __bool__ methods to the Structure, Model, Chain and Residue Python objects. The object will be truthy if it contains any child objects, and falsey if not. An empty container should be rarely encountered in normal use, but when using gemmi for model building, these conditions can arise.

For example:

structure = gemmi.read_structure("abcd.pdb")

if structure: 
    do_work()

This PR also adds a test file for these boolean comparisons in test_bool.py. After these changes, all gemmi tests in the tests folder pass.

wojdyr commented 3 months ago

Hi, thanks for taking time to open this PR.

I'd actually prefer checking len(structure) in such a case. The container-like interface is already somewhat confusing, because Structure has a number of properties; the container of Models is the most important property, but still one of many. On the other hand, for model in structure reads better than for model in structure.models, so I was tempted to use the former, although the latter would be more accurate. But I'd rather not go further with the container-like API.