CyberLX
CyberLX

Reputation: 275

How to access variables in another module with a string?

Assuming I have a module named Test1.py, and in it there are variables, say,

something = 10
apple = 5

I don't know these variables beforehand, they would be dynamically added from another module. So, how would I be able to access these variables in a different module given the variable's name as a string?

For example, I'd like to use the string 'apple' to access the apple variable from that module. In general, something like this:

# AnotherModule.py

import Test1

var = input('Variable: ')
print(Test1.var)

How to make that work if I enter apple as an input, and the result should be 5, since apple is 5 in the other module.

Upvotes: 1

Views: 622

Answers (1)

filmor
filmor

Reputation: 32202

You can use getattr for this:

getattr(Test1, var)

Upvotes: 3

Related Questions