nipy / nibabel

Python package to access a cacophony of neuro-imaging file formats

Home Page:http://nipy.org/nibabel/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unresolved attribute reference warning in Pycharm

pwrightkcl opened this issue · comments

I am using nibabel 5.1.0 in a script in Pycharm, and I'm getting highlighted warnings in code like this:

import nibabel as nib


image = nib.load('my_image.nii')
voxel_dims = image.header.get_data_shape()
Y = image.get_fdata()

# Do something to Y

new_image = nib.Nifti1Image(Y, image.affine, image.header)
  • Pycharm highlights get_data_shape with the warning Unresolved attribute reference 'get_data_shape' for class 'FileBasedHeader'.
  • Pycharm highlights get_fdata with the warning Unresolved attribute reference 'get_fdata' for class 'FileBasedImage'.
  • Pycharm highlights affine with the warning Unresolved attribute reference 'affine' for class 'FileBasedImage'.

The script seems to run OK, so it seems like an issue with Pycharm's checking. Looking at filebasedimages.py I don't see the get_data_shape method etc. so I guess those must be added when a child class specific to NIfTI images comes into play.

I don't know enough about Python namespaces and Pycharm's code checking, so I'm just going to leave this here for others to decide whether this requires any action on the nibabel side. If someone feels like dropping an educational reply, that would be an unexpected bonus.

Thanks, @effigies, that is informative. I can specify the type of my image object and clear the warnings as you describe in #1220.

image2 = nib.Nifti1Image.from_filename('my_image.nii')
voxel_dims2 = image2.header.get_data_shape()
Y2 = image2.get_fdata()
new_image2 = nib.Nifti1Image(Y, image2.affine, image.header)

I still get a warning for get_data_shape because the header is still default typed as FileBasedHeader. I can get that to go away as follows:

image3 = nib.Nifti1Image.from_filename('my_image.nii')
header3 = nib.Nifti1Header.from_fileobj(image3)
voxel_dims3 = header3.get_data_shape()

Thanks for the explanation.

I still get a warning for get_data_shape because the header is still default typed as FileBasedHeader

This seems like a bug in pycharm. It is detected as a nifti header by mypy. Happy to fix up the annotation to work with more tools, but I'll need advice from those familiar with them.

Also, if you just need the shape, img.shape ought to do the trick.