2

Possible Duplicate:
Does python have an equivalent to Java Class.forName()?

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

2 Answers 2

1

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, deserializaton) of the type names, which would essentially entail you repeating a bit of the work that pickle can already do on your behalf!-)

Sign up to request clarification or add additional context in comments.

Comments

0

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"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.