views:

227

answers:

4

Hello guys,
I'm using appengine to develop an application. Ideally I would like to define a new kind (called Recipe) like this:

class Recipe(db.Model):
    ingredients = db.ListProperty(type)
    quantities = db.ListProperty(int)

However it seems that you cannot use "type" as the class value in ListProperty. I was thinking of instead of using ListProperty, using ListStringProperty and save the class names as strings. However, how do I convert a string to a class name, so I can write like this:

str = "A"
# convert str to class name in var class_str
class_str().call_some_method()

Thanks in advance,
Jose

+1  A: 

Maybe the answers to this question will help you: Does python have an equivalent to Java Class.forName()?

gclj5
A: 

Maybe you can use eval, like this?

class Juice(object):
    def amount(self):
        print "glass of juice"

juice = "Juice"
eval(juice)().amount()
# prints "glass of juice"
sankari
A: 

What is type? If the individual ingredient types are datastore entities, you can use a ListProperty(db.Key) and store the Keys of the entities in question. You don't get the "magic" backreferences that a ReferenceProperty creates, nor will it enforce the db.Keys pointing to a particular class, but this would be the preferred way to have a list of references to other datastore entities.

Wooble
+1  A: 

I suggest you make ingredient a list of strings, populate it with the pickle.dumps of the types you're saving, and, upon retrieval, use pickle.loads to get a type object back.

pickle serializes types "by name", so there are some constraints (essentially, the types must live at the top level of some module), but that's way handier than doing your own serialization (and, especially, *de*serializaton) of the type names, which would essentially entail you repeating a bit of the work that pickle can already do on your behalf!-)

Alex Martelli