configparser: whitespace not stripped when writing empty values
Ninguém assumiu esta issue ainda.
- Linguagem predominante
- Python
- Estrelas
- 77.2k
- Forks
- 36k
- Métricas de merge de PRs
- Métricas de PR pendentes
Descrição
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
Guia de contribuição
Primeiros passos
- Leia a issue inteira e depois o guia de contribuição do projeto.
- Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
- Faça um fork do repositório e trabalhe em uma branch.
- Abra um pull request que referencie o número da issue.
Direção de pesquisa
Comece em ConfigParser.write() e _write_section(), que a issue identifica como os pontos de entrada que introduzem o espaço à direita. Adicione cobertura para a escrita de um valor vazio e verifique se a linha INI gerada não contém espaços em branco à direita; em seguida, execute os testes relevantes de configparser. Um PR vinculado já está indicado na issue.
Escrita pelo modelo de indexação a partir do texto da issue.
Avaliação
- Stack de tecnologia
- python
- Domínio
- tooling
- Tipo de issue
- Bug
- Dificuldade
- 2/5
- Tempo estimado
- 1-3 horas
- Status de atividade
- Estagnada
- Clareza
- Claramente especificada
- Facilidade para iniciantes
- 25/100