I see that the OP wanted JSON, but I do not want JSON and pprint is so close to giving me what I do want: black
-compatible Python source, which requires that I use "
instead of '
.
I settled on .replace("'", '"')
with pformat()
, although this is both ugly and fragile ☹️:
import pprint
# Note: my code auto-generates my_dict parsing a file (not black-formatted here)
my_dict = ["spam", "eggs", "lumberjack", "knights", "ni", "eggs", "lumberjack", "knights", "ni"]
pprinter = pprint.PrettyPrinter(indent=4)
formatted_code = (
pprinter.pformat(my_dict)
.replace("[ ", "[\n ") # break after opening bracket
.replace("']", "',\n]") # break before closing bracket, add comma
.replace("'", '"') # use double quotes
)
with open("example_module.py", "w", encoding="utf-8") as outfile:
outfile.write('"""Module containing auto-generated ALL_MR_HEADERS."""\n')
outfile.write(f"ALL_MR_HEADERS = {formatted_code}\n")
The resulting example_module.py is black
-compliant.
pprint()
just uses therepr()
result of the strings, which will use'
unless a literal'
quote is contained. – Roadabilityjson.dumps()
instead? JSON uses double quotes for strings... – Roadabilityjson.dumps()
does what I need. Can you post it as an answer? – Alienor