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

Community
  • 1
  • 1
user361526
  • 3,333
  • 5
  • 25
  • 36
  • Maybe the answers to this question will help you: [Does python have an equivalent to Java Class.forName()?](http://stackoverflow.com/questions/452969/) – gclj5 Jan 23 '10 at 08:24

2 Answers2

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

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
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"
sankari
  • 131
  • 6