Why transforms.ToTensor() behaves as a True when used in conditional statements?

Screenshot 2021-07-27 at 09-30-09 Docking ISS - Jupyter Notebook

I don’t think this behavior is specific to transforms.ToTensor(), but it seems that each valid object would return True in this condition:

if nn.Linear(1, 1):
    print('True')

if logging.Logger(name='test'):
    print('True')
1 Like

Oh. Thank you so much.
Can I know why?

I think it’s used to check, if an object is initialized, e.g. if it’s optional such as a transformation.
You would often see Python code as:

def __init__(self, transform=None): # initialize transform as None
    self.transform = transform

def __getitem__(self, x):
    if self.transform:
        x = self.transform(x)

and could use it with any other Python object as well.

1 Like

Thank you so much @ptrblck.