Python Forum

Full Version: Uncanny line of code in Torchat source file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have been sifting through Torchat's sourcecode, which is available on github: https://github.com/prof7bit/TorChat

I don‘t understand one line of code within the config.py file, in the get(section, option) method, that is.

def get(section, option):
    if not config.has_section(section):
        config.add_section(section)
    if not config.has_option(section, option):
        value = config_defaults[section, option]
        set(section, option, value)
    value = config.get(section, option)
    if type(value) == str:
        try:
            value = value.decode("UTF-8")
            value = value.rstrip(" \"'").lstrip(" \"'")
        except:
            print "*** config file torchat.ini is not UTF-8 ***"
            print "*** this will most likely break things   ***"
    elif type(value) == int:
        value = str(value)
    elif type(value) == float:
        value = str(value)

    return value # this should now be a unicode string
value = config_defaults[section, option] assigns a valu to the value variable, and evidently, this value is taken from the config_defaults dictionary:

config_defaults = {
    ("tor", "tor_server") : "127.0.0.1",
    ("tor", "tor_server_socks_port") : 9050,
    ("tor", "tor_server_control_port") : 9051,
    ("tor_portable", "tor_server") : "127.0.0.1",
    ("tor_portable", "tor_server_socks_port") : 11109,
    ("tor_portable", "tor_server_control_port") : 11119,
   
     ...
    
   ("profile", "text") : "",
} 
It is not normally possible to get a value from a python dictionary like this: config_defaults[section, option], is it?

I haven't been able to figure out what the line of code in question does or how it is supposed to work. Can anyone gve me a hint?
config_defaults is a dict that has tuples as keys.
And in this line value = config_defaults[section, option] section, option part is implicit tuple, so it's a valid code, effectively the same as value = config_defaults[(section, option)].

from the docs:
Quote:output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression).

>>> foo = 'spam', 'eggs'
>>> foo
('spam', 'eggs')
>>> type(foo)
<class 'tuple'>
>>> 
also, another example:


some_dict = {(1, 2):'one',
             (3, 4):'two'}
print(some_dict[1, 2])
Now I understand. thank you!