Exclude DEFAULT properties when reading with configparser

I am using Python 3.13.3.

I have configurations like:

[DEFAULT]
machines = machine1 machine2 machine3
foo = bar

[deployment]

	[machine1]
	tomcat = /home/user/install/tomcat
	dcpc = /home/user/install/dcpc


	[machine2]
	pe = /home/user/install/server
	dbloader = /home/user/install/server
	reqgen = /home/user/install/server


	[machine2]
	dcpc = /home/user/install/dcpc
	dcpc2 = /home/user/install/dcpc2
	dcpc3 = /home/user/install/dcpc3

And I do not know in advance what will be there exactly. I want then to go through each of those machines, connect to it and check what there is in those directories.

So I have this method:

    def get_modules_in_machines(self):
        modules_in_machines = list()

        machines = self.config["DEFAULT"]["machines"].split()
        for machine in machines:
            logger.debug(f"Reading config for {machine}")
            modules_in_machine = dict(self.config.items(machine, raw=True))
            logger.debug(f"Config is: {modules_in_machine}")

            modules_in_machines.append((machine, modules_in_machine))

        return modules_in_machines

That is NOT supposed to return foo: bar, but it does return it along the contents of the specified section; why? I thought the raw=True had to do exactly that: skip values in DEFAULT section.

Thank you very much for your help.

raw=True means that no interpolations happen, not that no values from DEFAULT are used.

I am not that familiar with configparser, but reading the docs there doesn’t appear to be a simple way to get only the values in the section ignoring DEFAULT.

Your best bet is to either not provide a default section (you seem to be using it slightly incorrectly anyway; maybe you want an unnamed section instead?) or to parse the file as if it didn’t have a default section and apply it manually if needed by setting the constructor argument to something that isn’t in the file.

OK. Then ChatGPT led me the wrong way :s

Thank you very much for the clarification. I think I will go with the renaming of the section.

You said I am using it wrong, could you hint me at what it is meant for? In what case does it make sense to use it?

DEFAULT is for if you have default values that should apply for all sections. E.g. in your example if you want to have a default user_name that is the same on most machines machine1, machine2, machine3, … The default section then allows you to not repeat the value unless it’s different on this one machine.

1 Like