Search code examples
pythonpython-2.7python-importraw-input

Print variable from other file with raw_input


So I'm just starting out on a project here. For starters, I have two files.

The first file is myDict.py. In there I store variables that I want to be able to fetch. myDict.py:

numbers = [1, 5, 8, 61]
wallet = [20, 50, 100, 1000]

So there I have two lists in that file, now to the mainfile. I wanted to choose which list I wanted to print from raw_input, but I don't know how I would be able to do that. I haven't directly gotten anywhere since I do not know how to be able to do this.

I know I can do this to print a selected variable from myDict.py:

import myDict
print myDict.wallet

But I can't find a way to do it with raw_input.


Solution

  • You can use the getattr() function to get arbitrary attributes named in a variable from the module:

    import myDict
    
    list_name = 'wallet'
    print getattr(myDict, list_name)
    

    Simply use raw_input() to ask the user for either wallet or numbers and you are set!

    import myDict
    
    list_name = raw_input('wallet or numbers? ')
    print getattr(myDict, list_name)
    

    You may want to use a try:/except AttributeError: to catch mistakes:

    list_name = raw_input('wallet or numbers? ')
    try:
        print getattr(myDict, list_name)
    except AttributeError:
        print "Sorry, no such list"