1

OK.

So I've got a database where I want to store references to other Python objects (right now I'm using to store inventory information for person stores of beer recipe ingredients).

Since there are about 15-20 different categories of ingredients (all represented by individual SQLObjects) I don't want to do a bunch of RelatedJoin columns since, well, I'm lazy, and it seems like it's not the "best" or "pythonic" solution as it is.

So right now I'm doing this:

class Inventory(SQLObject):
    inventory_item_id = IntCol(default=0)
    amount = DecimalCol(size=6, precision=2, default=0)
    amount_units = IntCol(default=Measure.GM)
    purchased_on = DateCol(default=datetime.now())
    purchased_from = UnicodeCol(default=None, length=256)
    price = CurrencyCol(default=0)
    notes = UnicodeCol(default=None)
    inventory_type = UnicodeCol(default=None)

    def _get_name(self):
        return eval(self.inventory_type).get(self.inventory_item_id).name

    def _set_inventory_item_id(self, value):
        self.inventory_type = value.__class__.__name__
        self._SO_set_inventory_item_id(value.id)

Please note the ICKY eval() in the _get_name() method.

How would I go about calling the SQLObject class referenced by the string I'm getting from __class__.__name__ without using eval()? Or is this an appropriate place to utilize eval()? (I'm sort of of the mindset where it's never appropriate to use eval() -- however since the system never uses any end user input in the eval() it seems "safe".)

4
  • couldn't this usage of eval be replaced with globals()[self.inventory_type]? Commented Dec 12, 2011 at 0:44
  • eval(self.inventory_type) is an imported class object (a subclass of the SQLObject class), not a variable. doesn't globals() only show declared variables? And SQLObject.get is not a @classmethod Commented Dec 12, 2011 at 1:05
  • 1
    if you import a module its name or the names imported appears in the return value of globals(). >>> import os / >>> 'os' in globals() / True Commented Dec 12, 2011 at 1:14
  • oh crap. You're right. If you make this an answer I'll accept it! Commented Dec 12, 2011 at 1:32

1 Answer 1

3

To get the value of a global by name; Use:

globals()[self.inventory_type]
Sign up to request clarification or add additional context in comments.

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.