1

I want to create this class by dynamically:

class CreateAgent(show.ShowOne):
    """Create compute agent command"""

    log = logging.getLogger(__name__ + ".CreateAgent")

    def get_parser(self, prog_name):
        parser = super(CreateAgent, self).get_parser(prog_name)
        parser.add_argument(
            "os",
            metavar="<os>",
            help="Type of OS")
        parser.add_argument(
            "architecture",
            metavar="<architecture>",
            help="Type of architecture")
        parser.add_argument(
            "version",
            metavar="<version>",
            help="Version")
        parser.add_argument(
            "url",
            metavar="<url>",
            help="URL")
        parser.add_argument(
            "md5hash",
            metavar="<md5hash>",
            help="MD5 hash")
        parser.add_argument(
            "hypervisor",
            metavar="<hypervisor>",
            help="Type of hypervisor",
            default="xen")
        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        compute_client = self.app.client_manager.compute
        args = (
            parsed_args.os,
            parsed_args.architecture,
            parsed_args.version,
            parsed_args.url,
            parsed_args.md5hash,
            parsed_args.hypervisor
        )
        agent = compute_client.agents.create(*args)._info.copy()
        return zip(*sorted(six.iteritems(agent)))

I went through many links but could find resources for dynamic class creation of classes with basic variables declarations and function.

class Foo(object):
    x = 10
    y = 20
    def get_x(self):
        return self.x
    def get_y(self):
        return self.y

Dynamic class creation can be done as:

Bar = type(
       'Bar',
       (object,),
       dict(
            x = 10,
            y = 20,
            get_x=lambda self:self.x,
            get_y=lambda self:self.y
        ) 
       )

But i don't know how to crete CreateAent class and define its functions dynamically..

This is the code that i have written:

def create_model(name, base=None, fields=None):
    model = type(name, base, fields)

    return model

if __name__ == '__main__':
    fields = {
        'os': str,
        'architecture': str,
        'version': int,
        'url': str,
        'md5hash': int,
        'hypervisor': int,
        }
    model = create_model('CreateAgent', ('Showone',), fields)
    model.os = "windows"
    print model.os
  1. It gives me the following error:

    TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

  2. I don't know how to define get_parser function.

PS: Some hints will be really helpful

3
  • generally you'd make some sort of a CreateAgentMaker function that returned a new class with your attributes. You can even use @classmethod to do it as CreateAgent.dynamic_from_string("name",(parents,), {"key":"value", "attri":"butes"}) Commented Jun 25, 2014 at 23:21
  • @AdamSmith I am mainly confused as to how to dynamically define class functions ? Can you help me with that Commented Jun 25, 2014 at 23:26
  • 1
    Give me a concrete example. What function you're trying to build from what arguments and we'll work on it. Commented Jun 25, 2014 at 23:29

1 Answer 1

2

In the type() command where you have (object,), you want to have

(show.ShowOne, object),

and where you have dict(...) you could also you an already existing dictionary:

def some_func(self):
    do_something()

cls_dict['some_func'] = some_func

and then your Bar creation would look like:

# towards the top of your file
import show

# somewhere else in your file...
Bar = type(
        'Bar',
        (show.ShowOne, object),
        cls_dict,
        )
Sign up to request clarification or add additional context in comments.

2 Comments

It gives error NameError: name 'show' is not defined
You have to import show prior to that line, same as you would for a normal class construction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.