Generating class definitions at runtime in memory from XSD or JSON

Nobody nobody at nowhere.com
Fri Feb 17 05:02:27 EST 2012


On Thu, 16 Feb 2012 17:15:59 -0800, Stodge wrote:

> Does anyone know of a library to generate class definitions in memory,
> at runtime, from XSD or JSON? I know about PyXB, generateDS and some
> others, but they all rely on generating python source files at the
> command line, and then using those to parse XML.

You don't need a library to generate classes. If the type() function is
called with 3 arguments, it creates and returns a new class. The first
argument is the name of the class, the second argument a tuple of base
classes, the third argument is the class' dictionary. E.g.:

	class Foo(Bar, Baz):
	    def __init__(self):
	        pass

could be written as:

	def foo_init(self):
	    pass

	Foo = type('Foo', (Bar, Baz), {'__init__': foo_init})

If you want to generate the function bodies from the contents of the
JSON or XML file, use exec().




More information about the Python-list mailing list