dynamic type returning NameError:

Tim O'Callaghan tocallaghan at gmail.com
Mon Jul 29 00:14:19 EDT 2013


On Sunday, July 28, 2013 10:51:57 PM UTC-4, Terry Reedy wrote:
> On 7/28/2013 9:38 PM, Tim O'Callaghan wrote:
> 
> > Hi,
> 
> >
> 
> > I hope that this hasn't been asked for the millionth time, so my apologies if it has.
> 
> >
> 
> > I have a base class (BaseClass - we'll call it for this example) with an http call that i would like to inherit into a dynamic class at runtime. We'll call that method in BaseClass;  'request'.
> 
> >
> 
> > I have a dictionary(json) of key (class name): value(method) that I would like to create inheriting this 'request' method from the BaseClass. So the derived class would look something like this
> 
> >
> 
> > definition in json:
> 
> > {"Whatever": [{"method1": "Some Default", "async": True},{"method2": "Some Other Default", "async": True}]}
> 
> >
> 
> > Ideally I'd like the class def to look something like this if i were to type it out by hand
> 
> >
> 
> > [excuse the indents]
> 
> >
> 
> > class Whatever(BaseClass):
> 
> >      def method1(self):
> 
> >          stupid_data = super(Whatever, self).request("method1")
> 
> >          return stupid_data
> 
> >
> 
> >       def method2(self):
> 
> >          stupid_data = super(Whatever, self).request("method1")
> 
> >          return stupid_data
> 
> >
> 
> > Now, I've been trying to do this using the python cli, with out success.
> 
> >
> 
> > So, attempting this at runtime I get a plethora of wonderful errors that I suspect has broken my brain.
> 
> >
> 
> > Here is what i've tried:
> 
> >
> 
> > # trying with just an empty object of type BaseClass
> 
> > obj = type("Object", (BaseClass,), {})
> 
> >
> 
> > whatever = type("WhatEver", (obj,), {"method1": super(WhatEver, self).request("method1")})
> 
> 
> 
> 'method1' has to be mapped to a function object.

But isn't that what calling super is doing? Calling the function object of the parent class BaseClass? 

> 
> > but when i try this I get 'NameError: name 'self' is not defined'
> 
> >
> 
> > defining these classes manually works...
> 
> >
> 
> > I hope that this was clear enough, apologies if it wasn't. It's late(ish), I'm tired and borderline frustrated :) But enough about me...
> 
> >
> 
> > Thanks in advance.
> 
> >
> 
> 
> 
> 
> 
> -- 
> 
> Terry Jan Reedy




More information about the Python-list mailing list