Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference variable dynamically in Python?

Tags:

python

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 ] 
like image 569
Luis Avatar asked Jun 22 '26 12:06

Luis


1 Answers

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

like image 166
Avishay Cohen Avatar answered Jun 24 '26 03:06

Avishay Cohen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!