dynamic type returning NameError:

Terry Reedy tjreedy at udel.edu
Sun Jul 28 22:51:57 EDT 2013


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 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