python / python/cpython

configparser: whitespace not stripped when writing empty values

Aperta
#157,466 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

stdlib type-feature
Lingua principale
Python
Stelle
77.2k
Fork
35.9k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug description:

When writing a configparser.ConfigParser to a file, keys with an empty value add a whitespace at the end of the line.

Eg. a line key = , ending with a whitespace.

import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ok': 'value', 'error': ''}
with open("test.ini", "w") as fhandle:
    config.write(fhandle)

Now the contents of test.ini are:

[DEFAULT]
ok = value
error = 

The line with the key "error" ends in a space. It appears the extra whitespace is introduced in ConfigParser.write(). Whitespaces are added to the delimiter, but this does not account for empty values.

class ConfigParser:
    def write(self, fp, space_around_delimiters=True):
        if space_around_delimiters:
            d = " {} ".format(self._delimiters[0])
        ...

Stripping the whitespace of the value in ConfigParser._write_section() solves this.

class ConfigParser:
    def _write_section(self, fp, section_name, section_items, delimiter, unnamed=False):
        if not unnamed:
            fp.write(f"[{section_name}]\n")
        for key, value in section_items:
            self._validate_key_contents(key)
            value = self._interpolation.before_write(
                self, section_name, key, value
            )
            if value is not None or not self._allow_no_value:
                # Convert all possible line-endings into '\n\t'
                value = (delimiter + str(value).replace('\r\n', '\n')
                         .replace('\r', '\n').replace('\n', '\n\t'))
            else:
                value = ""
            # Change from the original: strip empty space to avoid "key = " for
            # empty keys!!!
            line = f"{key}{value}".strip(" ")
            fp.write(f"{line}\n")
            # Done with changes.
        fp.write("\n")
CPython versions tested on:

3.14

Operating systems tested on:

Linux

Linked PRs
  • gh-157467

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Parti da ConfigParser.write() e _write_section(), che l’issue identifica come i punti di ingresso che introducono lo spazio finale. Aggiungi la copertura per la scrittura di un valore vuoto e verifica che la riga INI generata non contenga spazi bianchi finali, quindi esegui i test rilevanti di configparser. Nell’issue è già indicato un PR collegato.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
2/5
Tempo stimato
1-3 ore
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
25/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.