Is it possible to run the Python reformatter Black under Pythonista? If so, how?
Forum Archive
Is possible to run Black on Pythonista?
Should be.Try installing with pip, though you may need to install manually, pip does not like multiple modules which black has
You might need to disable the multiprocessing Manager import in black.py
@upwart, let us know how it goes.
For me, 4 space tabs are a bit of a killer, as I mostly edit on the phone, where horizontal space is limited.
@JonB
How do I manually install?
@mikael
Well, 4 spaces is the standard and seems perfect for me (on iPad Pro 10.5" and Windows).
Well try using stash, and pip install.
If that fails, use pip download. Then manually tar -xvf on the resulting file. Then mv the applicble folders/files into site-packages. You can manually look at the setup.py to get a feel for what folders or files it needs.
I was wondering the same thing, and I finally got this working. I think the problem was with the attrs package. One of the errors made it look like I needed attr (no 's'), but that is a different unrelated package.
I installed black with Stash pip, as well as attrs and any other package it needed, until I could run black.py without errors.
I put together this little script to format a document in the editor. I'm sure there's a better way to do it, but this seems to work beautifully when added to the tools menu in Pythonista.
#!/usr/bin/env python3
"""Format editor contents/selection in Pythonista with Black formatter."""
import editor
import black
import console
import time
# Options
LINE_LEN = 88 # Default: 88
FAST = False # True = skip syntax check
# Get text and selection
text = editor.get_text()
start, end = editor.get_selection()
selection = text[start:end]
if len(selection) > 0:
raw_text = selection
else:
raw_text = text
try:
start_tm = time.time()
formatted = black.format_file_contents(
raw_text, line_length=LINE_LEN, fast=int(FAST)
)
except black.NothingChanged:
console.hud_alert(
f"No formatting needed! ({time.time() - start_tm:.4f}s)", "success"
)
except Exception as err:
console.hud_alert(err, "error")
else:
new_text = formatted[:-1]
if len(selection) > 0:
editor.replace_text(start, end, new_text)
editor.set_selection(start, start + len(new_text))
else:
editor.replace_text(0, len(text), new_text)
editor.set_selection(start, end)
console.hud_alert(
f"Reformatted! ({time.time() - start_tm:.4f}s)", "success")
Trying to install black now, I have a problem installing regex dependency. regex seems to be a ”better re”, and unfortunately has a C component.
Has anyone worked around this?
@mikael
Hello,
You could try installing an old version of black from before regex was used, i.e. prior to 13 October 2019, I think... https://github.com/psf/black/pull/1047