I have couple of methods inside a class that control a virtual machine life-cycle. Operations like start, stop, terminate, retire .. etc
The code for these methods is almost identical, for example:
def stop(self, instances):
"""
Stop instance or a group of instances
:param instances: List of instances
:return:
"""
try:
response = self.ec2_client.stop_instances(InstanceIds=instances, DryRun=False)
print(response)
except ClientError as e:
print(e)
return response
def start(self, instances):
"""
Start instance or a group of instances
:param instances: List of instances
:return:
"""
try:
response = self.ec2_client.start_instances(InstanceIds=instances, DryRun=False)
print(response)
except ClientError as e:
print(e)
return response
As you can see, the two methods are almost identical except for the API call to perform the required action (start_instances and stop_instance).
Is there is a way to write such methods or functions in general and prevent repeating code?
Thanks in advance.
P.S. I was thinking of decorators, instance functions, closures -- but just don't know how!
Below answers inspired me to the following solution:
@staticmethod
def _request_action_method(action, instances):
instance_ids = FleetManager._instance_to_str(instances)
def _action_method():
try:
response = action(InstanceIds=instance_ids, DryRun=False)
print(response)
except ClientError as e:
print(e)
return _action_method
I could replace +50 lines of code with those few lines and it works :)