3

I have the following code:

PROJECT_ID = 'test'
BQ_TABLE_NAME_CATEGORIES = 'categories'
BQ_TABLE_NAME_MANUFACTURERS = 'manufacturers'
list = [BQ_TABLE_NAME_CATEGORIES, BQ_TABLE_NAME_MANUFACTURERS]
table_categories = PROJECT_ID + '.'  + BQ_TABLE_NAME_CATEGORIES
table_manufacturers = PROJECT_ID + '.' + BQ_TABLE_NAME_MANUFACTURERS

for table in list:
    ....
    source_objects=['table_{0}'.format(table)]  #reference to the correct var
    ....

This however puts string inside source_objects. I want it to reference the variables (whatever is saved in the variables) meaning what I actually want is equivalent of this:

When table = BQ_TABLE_NAME_CATEGORIES

source_objects = [ table_categories ] 

When table = BQ_TABLE_NAME_MANUFACTURERS

source_objects = [ table_manufacturers ] 
3
  • Are you trying to get the contents on table_categories inside a list? Or do you just want to reference it's string value? Commented Dec 19, 2018 at 9:24
  • Also, it is bad practice to override the built-in list object. Commented Dec 19, 2018 at 9:25
  • @RottenCandy I want the refrence... source_objects should contain whatever table_categories contains.. Just like I would do : source_objects = [ table_categories ] Commented Dec 19, 2018 at 9:26

2 Answers 2

5

you can use the eval() function to turn strings into variable: read on eval

PROJECT_ID = 'test'
BQ_TABLE_NAME_CATEGORIES = 'categories'
BQ_TABLE_NAME_MANUFACTURERS = 'manufacturers'
mylist = [BQ_TABLE_NAME_CATEGORIES, BQ_TABLE_NAME_MANUFACTURERS]
table_categories = PROJECT_ID + '.'  + BQ_TABLE_NAME_CATEGORIES
table_manufacturers = PROJECT_ID + '.' + BQ_TABLE_NAME_MANUFACTURERS

for table in mylist:
    source_objects=eval('table_{0}'.format(table)) #reference to the correct var
    print source_objects

output:

test.categories
test.manufacturers

also as noted in comments, you really shouldn't override list, and use mylist or whatever instead

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

Comments

3

If I understand your question correctly, what you are trying to do is store the values of table_categories and table_manufacturers inside a list called source_objects. Assuming the table_... variables are global,

suffixes = [BQ_TABLE_NAME_CATEGORIES, BQ_TABLE_NAME_MANUFACTURERS]

source_objects = []
for s in suffixes:
    source_objects.append(globals['table_{0}'.append(s)])
    ...

This would get you:

>>> source_objects
['test.categories', 'test.manufacturers']

And if the table_... variables are not global, use locals(). See https://docs.python.org/3/library/functions.html#globals

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.