1

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.

1
  • 2
    getattr(Test1, var) Commented Apr 27, 2017 at 16:50

1 Answer 1

3

You can use getattr for this:

getattr(Test1, var)
Sign up to request clarification or add additional context in comments.

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.