Hi Quants,

I wanted to share with you an advanced Python concept which can prove useful in algos to stop doing checks all the time once they are not necessary anymore. Note that this is an advanced concept and if you do not master more basic concepts of Python or if your do not master your algo, doing the following will only mess your algo big time. But when you know exactly where you are going, the following can prove useful in multiple occasions.

So, here is a very simple synthetic example to demonstrate the concept:

class Test:
    def __init__(self):
        self._field = None

    def Update(self, input):
        if self._field is None:
            self._field = input
            self.Update = self.Update_safe
            print("Update's implementation has been changed.")
    
    def Update_safe(self, input):
        print("Inside Update_safe.")
        if self._field == 1:
            print(input)

t = Test()
t.Update(1)
t.Update(2)

Imagine you have a class for which some fields cannot be initialized right at object construction time because you do not know which value to give them. In Test, such a field is “self._field”.

So you code your methods to initialize those fields when you have enough information. In Test, we do this in Update: here, we simply set _field to be the first value passed as input. Normally, one's implementation would first test _field and then do whatever is needed as calculations. Like so:

    def Update(self, input):
        if self._field is None:
            self._field = input
        
        if self._field == 1:
        	print(input)

So, we test if _field is None, if so, we set it, and then we use _field. The test “is None” would then be done each time Update is called…

But going back to the first code example, you can see that after setting a value for _field, we do

self.Update = self.Update_safe

which changes, dynamically, Update's implementation. It basically says that the current object's Update method is now Update_safe.

So, from now on, when Update is called, it is not the code inside Update which is executed but the code inside Update_safe. And Update_safe assumes that _field has been set so it does not test it.

In other words, the code that uses the Test class can call Update() repetitively, and the only time “is None” is checked is for the first call.

Now, for very quick tests like this one, all this is not necessary. But for more time-consuming checks, it can be a saver.

Fred