dynamically creating classes from text

Marco Nawijn nawijn at gmail.com
Tue Jan 24 14:00:30 EST 2012

On Jan 24, 6:22 pm, T H <turian9... at gmail.com> wrote:
> I’m new to python, sorry if my question is a bit naive, I was
> wondering if it is possible to parse some text (ie. from a text file
> or say html) and then dynamically create a class?
> for example lets say the contents of the text file is:
>      functionName: bark  arg1: numberBarks
>      functionName: run    arg1: howFast  arg2: howLong
> and then from the text dynamically create a class like the one below
> (including the functions and its implementation)
> class Dog:
>         def bark(self, numberBarks, myArg):
>                 print(‘numberBarks: ‘ + numberBarks)
>                 print(‘myArg’ + myArg)
>                 return
>         def run(self, howFast, howLong, myArg):
>                 print(‘howFast: ‘ + howFast)
>                 print(‘howLong’ + howLong)
>                 print(‘myArg’ + myArg)
>                 return
> I know my question is a bit far fetched. Anyhow if it is possible how
> is it done?
> Thanks so much for any help!


You could also take a look at the 'type' builtin. It can be used to
dynamically create a class. It allows you to specify the class name,
the bases and a dictionary containing the attributes. A simple

>> aClass = type('A', (object, ), { 'a' : 10, 'b' : 'Hello World' })
>> aobj = aClass()
>> aobj.__class__.__name__
>> aobj.a

The methods might be a little more difficult to attach to the class,
but I don't fully understand your problem. In particular, where does
the implementation of your methods come from?


More information about the Python-list mailing list