If a method is unavailable you probably have the wrong type

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the functions category.

Last Updated: 2021-05-16

With the fastai library, I was trying to transform what I thought was an ImageList. (This assumption was because method chaining often returns objects of the same type in other APIs I use.)

ImageList.
  from_csv(
     working_folder,
     working_folder/'cleaned.csv'
   )
  .split_by_rand_pct(valid_pct=0.25)
  .transform()

This gave me the error:

AttributeError: 'ImageList' object has no attribute 'transform'

What confused me was that I had very similar code elsewhere - and it worked in that context:

ImageList.
  from_csv(
     working_folder,
     working_folder/'cleaned.csv'
   )
  .split_by_rand_pct(valid_pct=0.25)
   # This line in the chain is the only difference
  .label_from_df()
  .transform()

I should have paid attention to the fact that there was an extra label_from_df method and that this changed the returned type from

<class 'fastai.data_block.ItemLists'>

to

<class 'fastai.data_block.LabelLists'>

where only the latter had the method I wanted.

Lesson

When a method that should be on an object seems unavailable, your first port of call should be to check if the object you sent the message to is in fact the type you expect it to be.

In Python, aside from looking at the object type, I could have introspected the available methods with dir(my_image_list) and seen that the transform method was missing.