Question

I'm using boto to manage some EC2 instances. It provides an Instance class. I'd like to subclass it to meet my particular needs. Since boto provides a query interface to get your instances, I need something to convert between classes. This solution seems to work, but changing the class attribute seems dodgy. Is there a better way?

from boto.ec2.instance import Instance as _Instance

class Instance(_Instance):
    @classmethod
    def from_instance(cls, instance):
        instance.__class__ = cls
        # set other attributes that this subclass cares about
        return instance
Was it helpful?

Solution

I wouldn't subclass and cast. I don't think casting is ever a good policy.

Instead, consider a Wrapper or Façade.

class MyThing( object ):
    def __init__( self, theInstance ):
        self.ec2_instance = theInstance 

Now, you can subclass MyThing as much as you want and you shouldn't need to be casting your boto.ec2.instance.Instance at all. It remains as a more-or-less opaque element in your object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top