Skip to content

Allow custom_field_map to override existing field types for thread safety #163

@eleftherioszisis

Description

@eleftherioszisis

Retrieving the field type in read_header and _write_header requires to access a global variable.

This introduces two serious issues:

  1. 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.
  2. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions