Code Monkey home page Code Monkey logo

jupyter-black's Introduction

jupyter-black

master: master branch build status

A simple extension for Jupyter Notebook and Jupyter Lab to beautify Python code automatically using Black. Fork of dnanhkhoa/nb_black with a few minor modifications:

Features

Once loaded, automatically format syntactically correct jupyter cells with black once they are run.

Enhancements compared to dnanhkhoa/nb_black:

  • Configurability:
    • Try to read black config from pyproject.toml if available
    • Override settings such as line length and black.TargetVersion if desired
  • Uses black.format_cell to greatly simplify the codebase
  • Adds tests
  • Slightly more responsive (no longer requires setTimeout and a delay)
  • Free software: MIT

Introduction

black is an extremely popular python formatter. Jupyter is an awesome way to run python. This extension helps you automatically blacken your jupyter.

Dependencies

  • Python >= 3.8
  • jupyterlab >=4 / notebook >= 7
    • older versions of notebook worked well until jupyter-black 0.4.0, but recent updates to notebook have done away with the old way of formatting cells
    • consider pinning to v0.3.4 if you're stuck on an older version of notebook
  • See setup.cfg

Quickstart

python3 -m venv .venv && source ./.venv/bin/activate
python3 -m pip install --upgrade pip
python3 -m pip install jupyter-black jupyter
python3 -m jupyter notebook

From here, there are two ways to load the extension:

Configurable (recommended):

import jupyter_black

jupyter_black.load()

To look at configuration options:

jupyter_black.load??

For example:

import black
import jupyter_black

jupyter_black.load(
    line_length=79,
    verbosity="DEBUG",
    target_version=black.TargetVersion.PY310,
)

The other way:

%load_ext jupyter_black

This will load the extension using your defaults from pyproject.toml if available, or use the black defaults.

Development Setup

  1. Clone the repo: git clone https://github.com/n8henrie/jupyter-black && cd jupyter-black
  2. Make a virtualenv: python3 -m venv .venv
  3. Activate venv, update pip, and install editable test/dev version:
$ source ./.venv/bin/activate
$ ./.venv/bin/python -m pip install --upgrade pip
$ ./.venv/bin/python -m pip install -e .[test,dev]

Notes:

  • Tests use playwright
  • You'll need to run this command (once) prior to running the tests:
    • python -m playwright install --with-deps firefox
  • tox will automatically run these installation steps (helpful for CI)
  • If desired, pass the --no-headless flag to pytest for local debugging
  • See also [dev-notes.txt]

TODO

Contribution ideas:

  • More tests, currently very basic
    • Ensure config is overridden in unsurprising ways
    • Ensure other config options are properly passed to black
    • Ensure that pyproject.toml is searched for properly

Contributing

Please see CONTRIBUTING.md and TODO.

Troubleshooting / FAQ

  • How can I install an older / specific version of jupyter black?
    • Install from a tag:
    • Install from a specific commit:
      • pip install git+git://github.com/n8henrie/jupyter-black.git@aabc123def456ghi789

Acknowledgements

Many thanks to dnanhkhoa/nb_black for the original version!

And of course many thanks to the black and jupyter teams.

Also, after establishing the repo and reserving the name on PyPI, I noticed there is another library of the same name: drillan/jupyter-black. It looks like there have been no commits in the last 2 years, and it was never put in PyPI, so I think at this point I'll continue with this name. Sorry if this causes any trouble or confusion. I'll note that @drillan's library probably does things the right way by installing as an nbextension.

Buy Me a Coffee

☕️

jupyter-black's People

Contributors

n8henrie avatar bryanwweber avatar

Stargazers

George Ho avatar Théo VINCENT avatar Rob Gering avatar  avatar David Reguera avatar Patrick Luo avatar Alex Louden avatar Apu avatar Guillaume David avatar Vijay Sarathy avatar Wes Turner avatar John Gunstone avatar Albert Kottke avatar  avatar Giorgi Kakulashvili avatar Manoj Subramanyam avatar  avatar Gareth Simons avatar Patrick Arnecke avatar Benson avatar Pareekshith Katti avatar Alexandre GAZAGNES avatar Aleksej avatar  avatar Taka avatar bilzard avatar  avatar Daniel Obraczka avatar Stefan Ulbrich avatar Rafal Wojdyla avatar Kiran Patel avatar Elijas Dapšauskas avatar Paul Heasley avatar Armin Berres avatar Robbie Clarken avatar Kouroche Bouchiat avatar Antonin RAFFIN avatar Piotr avatar Adrian Staniec avatar Sudarshan Koirala avatar Seyed Alireza Fatemi Jahromi avatar Matt Wittmann avatar Aristide avatar Erik avatar Anna Hope avatar Tomas Koranda avatar  avatar John Sandall avatar M Turner avatar dec00000 avatar Niklas Morberg avatar Dan Langsam avatar Christoph Deil avatar  avatar Marco Edward Gorelli avatar

Watchers

 avatar Adrian Tofting avatar Jason Nader avatar  avatar

jupyter-black's Issues

Intermittently not working in notebook

In windows, using notebook (not lab), it works most of the time but eventually stops working.

Just a tracking issue while I try to sort this out.

I wonder if it has to do with re-running cells, or perhaps cells that cause an error (e.g. black doesn't yet support match).

Javascript Error: Jupyter is not defined

  • Operating system and version: Ubuntu 20.04.2 LTS
  • Python version: Python 3.9.7
  • jupyter-black version:
jupyter-black                 0.1.1       /opt/conda/envs/myenv/lib/python3.9/site-packages pip
jupyter-client                7.0.6       /opt/conda/envs/myenv/lib/python3.9/site-packages pip
jupyter-core                  4.9.1       /opt/conda/envs/myenv/lib/python3.9/site-packages pip
jupyterlab-pygments           0.1.2        /opt/conda/envs/myenv/lib/python3.9/site-packages pip
jupyterlab-widgets            1.0.2       /opt/conda/envs/myenv/lib/python3.9/site-packages pip

JupyterLab itself is version 3.1.8

My Issue

I can %load_ext jupyter_black fine, but when I execute a cell to be formatted, this error appears as output to the cell where I loaded jupyter_black: Javascript Error: Jupyter is not defined

WHYT

I've tried with DEBUG, but there is no additional information:

image

When I install nb_black instead of jupyter_black formatting works:

image


Please make sure you've taken these steps before submitting a new issue:

  • Include the Python and jupyter-black version in your issue
  • Ensure you're running a supported version of Python
  • Run jupyter-black in debug mode if applicable and include
    relevant output
  • Search the existing (including closed) issues
  • Please use codeblocks for any code, config, program output, etc.

Installation Downgrades IPython and Black

Can you unpin the required versions?

  • Python version: 3.9
  • jupyter-black version: 0.3.1

Collecting jupyter-black
Downloading jupyter_black-0.3.1-py3-none-any.whl (7.7 kB)
Collecting black<23,>=21.9b0
Downloading black-22.8.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.5 MB)
|████████████████████████████████| 1.5 MB 3.0 MB/s
Collecting ipython<8,>=7.27.0
Downloading ipython-7.34.0-py3-none-any.whl (793 kB)
|████████████████████████████████| 793 kB 2.2 MB/s

TypeError is thrown when `pyproject.toml` contains options not used by `black.Mode`

  • Operating system and version: Linux
  • Python version: 3.11
  • jupyter-black version: 'v0.3.3'

My Issue

Loading this extension in a Jupyter notebook throws an error if your pyproject.toml contains keys/values not recognized by black.Mode but are valid options for black.

For example:

Configured with:

#pyproject.toml
[...]

[tool.black]
line-length = 88
target-version = ['py311']
include = '\.pyi?$'

[...]

On running jupyter_black.load(lab=False), the following traceback is produced:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[3], line 1
----> 1 jupyter_black.load(lab=False)

File ~/.mambaforge/envs/py311/lib/python3.11/site-packages/jupyter_black/jupyter_black.py:220, in load(ip, lab, line_length, target_version, verbosity, **black_config)
    217     black_config.update({"target_versions": set([target_version])})
    219 if formatter is None:
--> 220     formatter = BlackFormatter(ip, is_lab=lab, black_config=black_config)
    221 ip.events.register("pre_run_cell", formatter._format_cell)

File ~/.mambaforge/envs/py311/lib/python3.11/site-packages/jupyter_black/jupyter_black.py:65, in BlackFormatter.__init__(self, ip, is_lab, black_config)
     63 valid_options = set(t.get_type_hints(black.Mode))
     64 # config = {k: v for k, v in config.items() if k in valid_options}
---> 65 mode = black.Mode(**config)
     66 mode.is_ipynb = True
     67 self.mode = mode

TypeError: Mode.__init__() got an unexpected keyword argument 'include'

WHYT

I'd suggest filtering the options first prior to passing them to the mode object in jupyter_black.py.
For example, the following modification fixes the aforementioned problem:

# jupyter_black.py
class BlackFormatter:
        [...]
        # Override with passed-in config
        config.update(black_config)

        LOGGER.debug(f"config: {config}")
        valid_options = set(t.get_type_hints(black.Mode))
        config = {k: v for k, v in config.items() if k in valid_options}
        mode = black.Mode(**config)
        mode.is_ipynb = True
        [...]

Incidentally, the WHYT link is broken; looking up an archived copy yields a long blog post that the author themselves is ambivalent of and now no longer makes available even on their technical blog and should probably be removed from your GitHub Issue Template.


Please make sure you've taken these steps before submitting a new issue:

  • Include the Python and jupyter-black version in your issue
  • Ensure you're running a supported version of Python
  • Run jupyter-black in debug mode if applicable and include
    relevant output
  • Search the existing (including closed) issues
  • Please use codeblocks for any code, config, program output, etc.

Proposal for removing defensive upper version constraints for transient dependencies

  • Operating system and version: MacOS / Linux.
  • Python version: Python 3.9, 3.10, 3.11
  • jupyter-black version: 0.3.1

My Issue

Hi, Nathan, thanks for having created this package 🙇

I see that you have put an upper version constraint < 8 on ipython. This package therefore downgrades ipython for any dependents. I was just wondering if there any specific reason for why you have put the version constraint in place or not, is the current implementation incompatible with version 8 of the ipython API, or is it mainly a "defensive" constraint put in place before version 8 was released? ☺️

If it is the latter, a defensive upper constraint, might I suggest removing it? I will refer to this great read as my argument for doing so 🤓

Regardless what you decide, thanks in advance!

  • Jakob

jupyter-black is not working in PyCharm

Formatting Jupyter notebooks using jupyter-black does not work in PyCharm. The notebook begins with a cell:

%load_ext autoreload
%autoreload 2
import jupyter_black
jupyter_black.load()

However, executing this cell doesn't reformat the notebook. One workaround is to install the black extension in PyCharm. It would be ideal if jupyter-black worked seamlessly in PyCharm.

Black 22 not supported

The requirements for jupyter black excludes the newly stable release of black (version 22). It seems to work fine though, it is probably enough to update setup.cfg.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.