1

I'm trying to use someone else's code with my own, specifically, I want to grab a variables value from his sheet, but I won't know the variable name right away.

Let's say that he has script A.py with the following:

test_1 = "This is the first test"
test_2 = "This is the second test"

In my script, which we can call B.py, I have the following:

import A

answer = A.test_1
print(answer)

And this will print out:

This is the first test

The problem I have, in this example, is that I don't know whether I want 1 or 2, so instead I want to add it dynamically as needed by creating a new variable once I know which number I want.

x = 1
new_var = "test_" + str(x)

However, I can no longer call his variable anymore

answer = A.new_var
print(answer)

This will now result in an AttributError: module 'A' has no attribute 'new_var'

And I will get a syntax error if it try it this way:

answer = A."test_" + str(x)

Does anyone know how I could get around this?

Robert
  • 183
  • 2
  • 13

2 Answers2

4

Try:

getattr(A, new_var)

This is the same as A.test_{x}

ycx
  • 3,155
  • 3
  • 14
  • 26
1

Create a dictionary that you can index once you do know which you want.

tests = {
    'test_1': A.test_1,
    'test_2': A.test_2
}

print(tests["test_1"])

Note that this suggests that A should be defining the dict itself, rather than a series of numbered variables.

chepner
  • 497,756
  • 71
  • 530
  • 681