How to extract and then refer to variables defined in a python module?
Question: I'm trying to build a simple environment check script for my firm's test
environment. My goal is to be able to ping each of the hosts defined for a
given test environment instance. The hosts are defined in a file like this:

    
    
    #!/usr/bin/env python
    host_ip = '192.168.100.10'
    router_ip = '192.168.100.254'
    fs_ip = '192.168.200.10'
    

How can I obtain all of these values in a way that is iterable (i.e. I need to
loop through and ping each ip address)?

I've looked at local() and vars(), but trying do something like this:

    
    
    for key, value in vars():
        print key, value
    

generates this error:

    
    
    ValueError: too many values to unpack
    

I have been able to extract the names of all variables by checking
`dir(local_variables)` for values that don't contain a '__' string, but then I
have a list of strings, and I can't figure out how to get from the string to
the value of the same-named variable.


Answer: First off, I strongly recommend not doing it that way. Instead, do:

    
    
    hosts = {
        "host_ip": '192.168.100.10',
        "router_ip": '192.168.100.254',
        "fs_ip": '192.168.200.10',
    }
    

Then you can simply import the module and reference it normally--this gives an
ordinary, standard way to access this data from any Python code:

    
    
    import config
    for host, ip in config.hosts.iteritems():
        ...
    

If you do access variables directly, you're going to get a bunch of stuff you
don't want: the builtins (`__builtins__`, `__package__`, etc); anything that
was imported while setting up the other variables, etc.

You'll also want to make sure that the context you're running in is different
from the one whose variables you're iterating over, or you'll be creating new
variables in locals() (or vars(), or globals()) while you're iterating over
it, and you'll get `"RuntimeError: dictionary changed size during iteration"`.

