Python Forum

Full Version: How to read module/class from list of strings?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I get 'string_wrong' to print out what 'correct' is printing out?

from google.cloud import bigquery

corret = [bigquery.SchemaField("field1","STRING", mode="NULLABLE"),
bigquery.SchemaField("field2","STRING", mode="NULLABLE")]

string_wrong = ['bigquery.SchemaField("field1","STRING", mode="NULLABLE")',
'bigquery.SchemaField("field2","STRING", mode="NULLABLE")']

print(corret)
print(string_wrong)
correct output:
Output:
[SchemaField('field1', 'STRING', 'NULLABLE', None, None, (), None), SchemaField('field2', 'STRING', 'NULLABLE', None, None, (), None)]
string_wrong output:
Output:
['bigquery.SchemaField("field1","STRING", mode="NULLABLE")', 'bigquery.SchemaField("field2","STRING", mode="NULLABLE")']
This is related to your other post? https://python-forum.io/thread-40853.html

You cannot "convert" string_wrong into correct. string_wrong is a str and correct is list containing the return value of a function call. What you could do is evaluate the python expresssion in string_wrong. It might return the same result.
correct = [5 + 2]
wrong = "[5 + 2]"
resolved = eval(wrong)
print(correct)
print(wrong)
print(resolved)
Output:
[7] [5 + 2] [7]
Be aware that eval(expression) executes the expression, any valid expression. The expression could add two numbers, or it could format your hard drive. Only use eval() if you know what expressions will be evaluated.