Retrieving the field type in read_header and _write_header requires to access a global variable.
This introduces two serious issues:
- Using in the same code
pynrrd in combination with another library that changes the globals, e.g. SPACE_DIRECTIONS_TYPE, may result in unexpected behavior because importing the latter would affect how the former works.
- Thread safety
While 1. can be solved with a context manager that changes the globals for the read/write operations and then restores them, 2. cannot be guaranteed when many threads needs to change and restore that global.
I would strongly suggest to avoid using globals in pynrrd, however I understand that changing the public API is difficult and takes time. For this reason I would like to suggest a workaround that would require to adapt how the custom_field_map is used.
In:
|
def _get_field_type(field: str, custom_field_map: Optional[NRRDFieldMap]) -> NRRDFieldType: |
the custom_field_map is used only for extra/unknown fields. However, this could be adapted to allow overrides if those are specified in the custom_field_map. This way the:
elif field in ['space directions']:
return nrrd.SPACE_DIRECTIONS_TYPE
would become:
elif field in ['space directions']:
return custom_field_map.get("space directions", nrrd.SPACE_DIRECTIONS_TYPE)
And ideally nrrd.SPACE_DIRECTIONS_TYPE could become a default value instead of a global that the user can change.
Retrieving the field type in
read_headerand_write_headerrequires to access a global variable.This introduces two serious issues:
pynrrdin combination with another library that changes the globals, e.g. SPACE_DIRECTIONS_TYPE, may result in unexpected behavior because importing the latter would affect how the former works.While 1. can be solved with a context manager that changes the globals for the read/write operations and then restores them, 2. cannot be guaranteed when many threads needs to change and restore that global.
I would strongly suggest to avoid using globals in pynrrd, however I understand that changing the public API is difficult and takes time. For this reason I would like to suggest a workaround that would require to adapt how the
custom_field_mapis used.In:
pynrrd/nrrd/reader.py
Line 90 in fa37782
the
custom_field_mapis used only for extra/unknown fields. However, this could be adapted to allow overrides if those are specified in thecustom_field_map. This way the:would become:
And ideally
nrrd.SPACE_DIRECTIONS_TYPEcould become a default value instead of a global that the user can change.