ICSM / ampere

A tool to fit the SED and spectra of dusty objects to constrain, among other things, the dust properties and mineralogy
6 stars 2 forks source link

Getters and setters for data and inference objects #68

Open pscicluna opened 1 year ago

pscicluna commented 1 year ago

A lot of important instance attributes are currently set in __init__ and then we trust users to set them sensibly if they change them. This could be improved by using getters and setters to protect the attributes and ensure that the appropriate processing is always done to them when setting their value, and that the correct value is returned - this will help make a clean representation for e.g. printing to the terminal.

The idea behind getters and setters in python is based on properties, and the basic gist of how to use them is:


class SomeClass:

    def __init__(self, someAttribute):
        self.someAttribute = someAttribute

    @property #This decorator tells python that the name of the following method should be registered as a property, and the method used as the _getter_ for that property. We will define the setter afterwads
    def someAttribute(self):
        #:Let's say we want to work with the log of this attribute internally so that it is always positive, but still tell the end user about the value, rather than its log
        return 10**self._someAttribute #we use the _ notation to indicate that users shouldn't interact with the variable directly, only with the getter and setter (since python doesn't have real private members)

    @someAttribute.setter
    def someAttribute(self, value):
        self._someAttribute = np.log10(value) #we're working with the log internally, so the setter has to store the log 

    def logBaseSomeAttribute(self, value):
        #now we're going to do something that depends on the log of someAttribute:
        return np.log10(value) / self._someAttribute #by storing the log ahead of time, we make a microscopic saving in time here.

Hopefully that makes sense! We should use this approach to ensure that e.g. samplers get rebuilt whenever any parameters of them change, or that units are properly checked when a user updates their data, etc.