3

Suppose I am building a composite set of types:

def subordinate_type(params):
   #Dink with stuff
   a = type(myname, (), dict_of_fields)
   return a()

def toplevel(params)
    lots_of_types = dict(keys, values)
    myawesomedynamictype = type(toplevelname, (), lots_of_types)

    #Now I want to edit some of the values in myawesomedynamictype's 
    #lots_of_types. 

    return myawesomedynamictype()

In this particular case, I want a reference to the "typeclass" myawesomedynamictype inserted into lots_of_types.

I've tried to iterate through lots_of_types and set it, supposing that the references were pointed at the same thing, but I found that the myawesomedynamictype got corrupted and lost its fields.

The problem I'm trying to solve is that I get values related to the type subordinate_type, and I need to generate a toplevel instantiation based on subordinate_type.

8
  • Could you post some toy code that demonstrates the problem? Commented Aug 3, 2010 at 16:51
  • why your base class is not object? Commented Aug 3, 2010 at 17:06
  • @SilentGhost: it doesn't seem needful. Commented Aug 3, 2010 at 17:17
  • But for what specific purpose did you need a reference to the "typeclass" myawesomedynamictype inserted into lots_of_types? This can only be to access a constructor, method (or member) later, or else for type checking, or implementing inheritance in some weird way. None of which sound Pythonic - what do you later use that reference for? Commented Jul 1, 2011 at 6:42
  • @smci: I have no clue anymore as to the specifics of the problem. This was nearly a year ago. I was doing some metaprogramming. Commented Jul 1, 2011 at 15:55

1 Answer 1

1

This is an ancient question, and because it's not clear what the code is trying to do (being a code gist rather than working code), it's a little hard to answer.

But it sounds like you want a reference to the dynamically created class "myawesomedynamictype" on the class itself. A copy of (I believe a copy of) the dictionary lots_of_types became the __dict__ of this new class when you called type() to construct it.

So, just set a new attribute on the class to have a value of the class you just constructed; Is that what you were after?

def toplevel(params)
    lots_of_types = dict(keys, values)
    myawesomedynamictype = type(toplevelname, (), lots_of_types)
    myawesomedynamictype.myawesomedynamictype = myawesomedynamictype
    return myawesomedynamictype()
Sign up to request clarification or add additional context in comments.

Comments

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.