When creating result objects within a class, is it possible to use __slots__
in this example? I thought I could get it to work by passing '__slots__'
into the dictionary for the third argument to type
:
class GeocodeResult(object):
"""class to handle Reverse Geocode Result"""
__slots__ = ['geometry', 'response', 'spatialReference',
'candidates', 'locations', 'address', 'type', 'results']
def __init__(self, res_dict, geo_type):
RequestError(res_dict)
self.response = res_dict
self.type = 'esri_' + geo_type
self.spatialReference = None
self.candidates = []
self.locations = []
self.address = []
if 'spatialReference' in self.response:
self.spatialReference = self.response['spatialReference']
# more stuff
@property
def results(self):
results = []
for result in self.address + self.candidates + self.locations:
result['__slots__'] = ['address', 'score', 'location', 'attributes']
results.append(type('GeocodeResult.result', (object,), result))
return results
def __len__(self):
"""get length of results"""
return len(self.results)
For the results
property, I want to build a list of small, light-weight objects with 4 properties: ['address', 'score', 'location', 'attributes']
The resulting object is created, and I can even get at the slots, but it is still keeping the __dict__
. Since there could potentially be hundreds of result objects, I want only the four properties listed above to save space.
Example:
>>> rev = GeocodeResult(r, 'reverseGeocode')
>>> result = rev.results[0]
>>> result.__slots__
['address', 'score', 'location', 'attributes']
>>> hasattr(result, '__dict__')
True
>>>
Is there a better way of doing this? Or do I have to define an explicit class to handle this?