Skip to content

DataCaching.py #1

Open
Open

Description

@akaRem

Since in Line._init__(..) you say self.start = start, self.start is free for change, and in Line.length(..) you must check if Line attrs has changed from the point when DataCache was setted.

Options are:
mark as private self.start -> self._start
or remember hash of relevant data when you set DataCache

Activity

  1. stefaneidelloth commented on Jan 29, 2021

    @stefaneidelloth

    If the attributes are considered to be private, the length could be calculated in the constructor and saved as a constant, without using a cache.

    => There should be a setters for the coordinates, resetting the cache.

    The __nonzero__ method is not called in python 3. => Rename to __bool__.

    import math
    
    class DataCache(object):
        """ A class representing cachable data"""
    
        def __init__(self):        
            self._data = None
    
        def __call__(self):      
            return self._data
    
        def __bool__(self):       
            """ 
            Called on bool(instance) or if(instance) returns if there is data 
            cached.
            e.g
            if (not data):
                # set data
            """
            return self._data is not None
        
        def set(self, data):     
            self._data = data
            
        def reset(self):      
            self._data = None
    
    class Line(object):
        """ 
        This is a class representing a 2D line.
        Takes a start point and end point represented by two pairs.
        The length is cached, so that it does not need to be re-calculated
        as long as the coordinates do not change.
        """
        
        def __init__(self, start, end):
           
            self._start = start
            self._end = end
            self._length_data = DataCache()
            
        def set_start(start):
            self._start = start
            self._length_data.reset()
            
        def set_end(end):
            self._end = end
            self._length_data.reset()
            
        def length(self):
            if (not self._length_data):
                x_length = self._start[0] - self._end[0]
                y_length = self._start[1] - self._end[1]
                length = math.sqrt((x_length ** 2) + (y_length ** 2))
                self._length_data.set(length)
            else:
                print("Cached value used")
            return self._length_data() # <= this is possible due to __call__ method
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions