I came across a piece of code today that looks like this:
class ClassName(object):
def __init__(self):
self._vocabulary = None
def vocabulary(self):
self._vocabulary = self._vocabulary or self.keys()
return self._vocabulary
What exactly is the line self._vocabulary = self._vocabulary or self.keys() doing?
A line like this:
Is what’s called lazy initialization, when you are retrieving the value for the first time it initializes. So if it has never been initialized
self._vocabularywill beNone(because the__init__method had set this value) resulting in the evaluation of the second element of theorsoself.keys()will be executed, assigning the returning value toself._vocabulary, thus initializing it for future requests.When a second time
vocabularyis calledself._vocabularywon’t beNoneand it will keep that value.