I'm writing an AI state space search algorithm, and I have a generic class which can be used to quickly implement a search algorithm. A subclass would define the necessary operations, and the algorithm does the rest.
Here is where I get stuck: I want to avoid regenerating the parent state over and over again, so I have the following function, which returns the operations that can be legally applied to any state:
def get_operations(self, include_parent=True):
ops = self._get_operations()
if not include_parent and self.path.parent_op:
parent_inverse = self.invert_op(self.path.parent_op)
getattr() to get the attribute, and
callable() to verify it is a method:
invert_op = getattr(self, "invert_op", None) if callable(invert_op): invert_op(self.path.parent_op)
getattr() normally throws exception when the attribute doesn't exist. However, if you specify a default value (
None, in this case), it will return that instead.