Ryan Folks
Ryan Folks

Reputation: 78

Is there a way to overload len() so that I don't have to use an int?

I am creating a class that works with time ranges,

class Time_Range:
    """A class that models time ranges."""
    
    def __init__(self, start:str, end:str, time_format='%m/%d/%Y %H:%M'):
        """Creates a time range.
        
        Parameters:
            start : str - start time.
            end : str - end time.
        """
        start_time = datetime.strptime(start, time_format)
        end_time = datetime.strptime(end, time_format)
        
        if start_time > end_time:
            raise ValueError("End time is before start time.")
        
        self.start = start_time
        self.end = end_time
    
    def __len__(self):
        """Returns the elapsed time in the time range."""
        return self.end - self.start

I defined len() to be the time elapsed as a timedelta object, but im getting an error
"TypeError: 'datetime.timedelta' object cannot be interpreted as an integer"

In my opinion, this is a perfectly reasonable way to implement len() in this class, but Python won't allow it. Is there a better way to do this? Do I have to resort to writing my own length method?

Upvotes: 0

Views: 140

Answers (1)

Roland Smith
Roland Smith

Reputation: 43533

It seems you are trying to fit something that isn't into a class.

If your class has only two methods, one of which is __init__, then (in general) it should be a function instead:

def time_range(start:str, end:str, time_format='%m/%d/%Y %H:%M'):
    start_time = datetime.strptime(start, time_format)
    end_time = datetime.strptime(end, time_format)
    
    if start_time > end_time:
        raise ValueError("End time is before start time.")

    return end_time - start_time

Especially since you are producing a TimeDelta anyway.

Upvotes: 1

Related Questions