Search code examples
pythondictionaryconfigparser

I do not understand how this Python code works - Unknown programming concept


My apologies for the crappy headline. If I were able to frame my problem properly I would have used google ;)

I found an piece of python code able to parse ini files into a python dict called "store":

#!/usr/bin/env python

from ConfigParser import SafeConfigParser

def read(file, store):

    def parse_maybe(section):
        if not confp.has_section(section):
            return False

        if (section == "Main"):
            for left, right in confp.items(section):
                store[left] = right.format(**store)
        return True

    confp = SafeConfigParser()
    confp.read(file)
    parse_maybe("Main")

store = {}
store["basedir"] = "/path/to/somewhere"
read("foo.ini", store)

The ini files may include declarations with placeholders, for instance:

[Main]
output = {basedir}/somename.txt

When running the code, {basedir} gets replaced by "/path/to/somewhere" already defined in store. I guess this magic comes from this line of code:

store[left] = right.format(**store)

I understand what the code does. But I do not understand how this works. What is this ** operator doing with the dictionary? A pointer to a tutorial, etc. would be highly appreciated.


Solution

  • The answer to my question is twofold:

    1) I did not know that this is possible with format:

    print "{a} is {b}".format(a="Python", b="great")
    

    Python is great

    2) Essentially the ** Operator unpacks a dictionary:

    dict = {"a": "Python", "b": "great"}
    print "{a} is {b}".format(**dict)
    

    Python is great