Pre-Doc: Working with type hints #1220
Replies: 1 comment
-
Loading imagesPreviously, we recommended using the universal loading function: import nibabel as nib
img = nib.load('bold.nii.gz') Because of the number of formats that can be handled by If you know the type of image you're working with, the most precise way to let type checkers know is to use the img = nib.Nifti1Image.from_filename('bold.nii.gz') Here, the type checker will know that you have a img: nib.spatialimages.SpatialImage = nib.Nifti1Image.from_filename('bold.nii.gz') You can also write your own helper function that allows you to dynamically declare the API you want available at check time and raise an error if unsatisfied at runtime: from typing import TypeVar
import nibabel as nib
ImgT = TypeVar('ImgT', bound=nib.filebasedimages.FileBasedImage)
def load_api(fname: str, api: type[ImgT]) -> ImgT:
img = nib.load(fname)
if not isinstance(img, api):
raise TypeError(f'File {fname} does not implement {api} interface')
return img
img = load_api('test.nii.gz', nib.spatialimages.SpatialImage) # Succeeds
img = load_api('test.nii.gz', nib.Nifti2Image) # Fails with Nifti1Image, passes with Nifti2Image This provides you with the dynamic detection of types that |
Beta Was this translation helpful? Give feedback.
-
Since 5.0, we've been starting to add type hints to NiBabel in order to enable using type checkers to catch bugs or allow type-aware IDEs to provide auto-complete suggestions.
While the API hasn't changed, these type-aware tools may promote different default practices. I want to start this discussion as a place to work out a new set of recommendations and eventually promote this to a document to go on the website.
Beta Was this translation helpful? Give feedback.
All reactions