How to modify internal ImageFolder object after creation?

I am trying to port some dataloader codes from codebase 1 to codebase 2.
For codebase 2, the dataloader was based on ImageFolder, while the dataloader in codebase 1 was something where. What I did was to replace the getitem of codebase2 with the one from codebase1, and it worked well.

However, the other part of codebase 2 (which I cannot modify due to some internal policy) will read the total number of samples by doing len(train_loader), where “train_loader” is the ImageFolder object.

So I am thinking if I can hack it a little bit to modify the attributes of this ImageFolder object “train_loader”, so that len(train_loader) will return the desired value. I need to do that after this object was created, and I tried “self.samples = []” to see whether len(train_loader) will become 0, but nothing happened.

Could someone provide some guidance on this? Thanks.

Removing all internal self.samples should work, as the DatasetFolder class uses this attribute to get the length as seen here.
Alternatively, you could also try to monkey-patch the __len__(self) method and assign the desired value to it, assuming you want to reduce the number of samples and remove the last samples.
With that being said, I don’t know what your use case is and would generally recommend to create either a new Dataset with the desired attributes or create a custom one.

1 Like