views:

141

answers:

3

Hi-- I think this is probably something really simple, but I'd appreciate a hint:

I am using a python list to hold some some database insert statements:

list = [ "table_to_insert_to" ],["column1","column2"],[getValue.value1],["value2"]]

The problem is one of the values isn't evaluated until runtime-- so before the page even gets run, it breaks when it tries to import the function.

How do you handle this?

+2  A: 

Just wrap it in a function and call the function when you have the data to initialize it.

# module.py

def setstatement(value1):
    global sql
    sql = ['select', 'column1', 'column2', value1]

# some other file
import module
module.setstatement(1)

# now you can use it.
>>> module.sql
['select', 'column1', 'column2', 1]
Unknown
+3  A: 

You've just pointed out one (out of a zillion) problems with global variables: not using global variables is the best solution to this problem and many others. If you still mistakenly believe you must use a global variable, put a placeholder (e.g. None) in the place where the value you don't yet know will go, and assign the right value there when it's finally known.

Alex Martelli
+1  A: 

May be put functions instead of value, these functions should be called at run time and will give correct results e.g.

def getValue1Func():
    return getValue.value1

my_list = [ "table_to_insert_to" ],["column1","column2"],[getValue1Func],["value2"]]

now I do not know how you use this list(I think there will be better alternatives if you state the whole problem), so while using list just check if value is callable and call it to get value

e.g.

if isinstance(val, collections.Callable):
    val = val()

edit: for python < 2.6, you should use operator.isCallable

Anurag Uniyal