DEV Community 👩‍💻👨‍💻

Cover image for Black with Docker
Constantine
Constantine

Posted on • Updated on

Black with Docker

Photo by Jan Kopřiva on Unsplash

Fromatting Python code remotely with PyCharm

I'm sure you've heard about Black, a formatter for Python. It's opinionated, but really good. One thing I disagree with - is double quotes everywhere. I prefer single. But that is disable-able.

So, what's Docker doing here? Well, you can run Black as a service. Meaning you can skip installation on a local machine and deploy straight with containers.

Dockerfile

I've published a final image so you can just pull that from dockerhub. Or build it yourself. Here we go with a multi-stage build to make our container slim.

FROM python:3.9-slim AS builder
RUN apt update && apt install -y git build-essential \
    && pip install --upgrade pip setuptools wheel black[d]

FROM python:3.9-slim
COPY --from=builder /usr/local/ /usr/local/
EXPOSE 45484
ENTRYPOINT ["blackd", "--bind-host", "0.0.0.0", "--bind-port", "45484"]
Enter fullscreen mode Exit fullscreen mode

First we build a builder image, installing dependencies and Black itself. Then we just copy what we need from builder to the final image. That way we'll have around 160 Mb in size.

Now you can build with:

docker build . -t blackd:latest
Enter fullscreen mode Exit fullscreen mode

Container

Let's go to "Containers" side-menu in Portainer and smash the "Add container" button. Set:

  • name: blackd
  • image: blackd:latest OR ceeveeya/blackd:latest
  • publish port: 45484:45484

A handy screenshot:
Blackd create container

And press "Deploy".

Usage

Now when we have working Black service all is left - to use that.

Pycharm

Add BlackConnect plugin and set config as on the screenshot below.

BlackConnect config

VSCode

Unfortunately, I couldn't find a similar extension for this IDE. But I'm not using VSCode for python development so.. ¯\_(ツ)_/¯ Let's hope somebody will make something like BlackConnect one day 😅


Now your code should be formatted every time you save it!

Top comments (0)

DEV runs on 100% open source code known as Forem.

 
Contribute to the codebase or host your own.
 
Check these out! 👇