Giter Club home page Giter Club logo

jupyter-black's Introduction

Jupyter Black [Black formatter for Jupyter Notebook]

This extension reformats/prettifies code in a notebook's code cell by black.

demo

pre-requisites: of course, you must have some of the corresponding packages installed:

pip install black [--user]

Then the extension provides

  • a toolbar button
  • a keyboard shortcut for reformatting the current code-cell (default: Ctrl-B)
  • a keyboard shortcut for reformatting whole code-cells (default: Ctrl-Shift-B)

Syntax shall be correct. The extension will also point basic syntax errors.

Installation

If you use jupyter-contrib-nbextensions, proceed as usual.

Otherwise, you can still install/try the extension from personal repo, using

jupyter nbextension install https://github.com/drillan/jupyter-black/archive/master.zip --user
jupyter nbextension enable jupyter-black-master/jupyter-black

jupyter-black's People

Contributors

drillan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

jupyter-black's Issues

Please add a License

Hi @drillan
thanks a lot for putting effort in this extension.

I really do like it and use it a lot in personal projects now.
However I can't legally use it at work since there is no license attached.

(Of course for my use-case I would prefer a rather "open" one, but that should be left to your decision see choose a license)

Therefore I'm kindly asking you to pick a license and add it to the repository.
Thanks
Martin.

Cannot apply on multiple cells

Like jupyter-black :)

I found one small glitch: when selecting multiple cells and then applying black, it applies to only the last cell. I hope we could make it apply on all selected cells instead.

Thanks,
Kwat

[Question]: How to use via commandline

Hi!

I was wondering if it's possible to run this extension via the commandline, say something along the lines of

python3 -m jupyter-black demo.ipynb

which formats all the cells in demo.ipynb. Thanks in advance!

how to configure?

hello! very nice extension! I use black in my python repositories, and I have some specific configurations for example I like to set the max-line-length to 140. is it possible to do that with this extension?

`cell_census.get_anndata()` cannot query using `is_primary_data`

The following runs properly:

import cell_census
import scanpy as sc
census = cell_census.open_soma(census_version="latest")

lung_adata = cell_census.get_anndata(census, 
                                     organism = "Homo sapiens", 
                                     obs_query = {"tissue_general": "lung"},
                                     var_query = {"feature_name": ["MALAT1", "AQP5"]}
                                    )

the following produces the error below, the only difference is querying by is_primary_data

import cell_census
import scanpy as sc
census = cell_census.open_soma(census_version="latest")

lung_adata = cell_census.get_anndata(census, 
                                     organism = "Homo sapiens", 
                                     obs_query = {"tissue_general": "lung", "is_primary_data": True},
                                     var_query = {"feature_name": ["MALAT1", "AQP5"]}
                                    )

error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In [15], line 1
----> 1 lung_adata = cell_census.get_anndata(census, 
      2                                      organism = "Homo sapiens", 
      3                                      obs_query = {"tissue_general": "lung", "is_primary_data": True},
      4                                      var_query = {"feature_name": ["MALAT1", "AQP5"]}
      5                                     )

File ~/scripts/repos/cell-census/api/python/cell_census/src/cell_census/get_anndata.py:118, in get_anndata(census, organism, measurement_name, X_name, obs_query, var_query, column_names)
    115 if exp.soma_type != "SOMAExperiment":
    116     raise ValueError(f"Unknown organism {organism} - not a SOMA Experiment")
--> 118 _obs_query = _build_query(obs_query)
    119 _var_query = _build_query(var_query)
    120 with experiment_query(exp, measurement_name=measurement_name, obs_query=_obs_query, var_query=_var_query) as query:

File ~/scripts/repos/cell-census/api/python/cell_census/src/cell_census/get_anndata.py:57, in _build_query(query_defn)
     55         query_conditions.append(f"{name} in {val}")
     56     else:
---> 57         raise TypeError("Query must be string or list of strings")
     59 if len(query_conditions) == 0:
     60     return None

TypeError: Query must be string or list of strings

How to set line length?

The issue title pretty much says it all. This extension is perfect for me, but I would really appreciate some way to set the line length from the parameters editor provided in the jupyter nbextensions configurator. Thanks!

Black is needed in the kernel, not the environment running jupyter, but the reverse is preferred.

Currently it seems that this extension needs to be able to import black from the running kernel, which means that the environment running the kernel must have black installed (it is actually not needed in the environment running jupyter).

This should be documented, however, it would be better if the reverse were true: i.e. if black only needed to be installed in the environment running jupyter. The reason is that one often needs to keep the kernel as clean as possible (minimal locked dependencies) for reproducibility, and requiring black or other "tools" to be installed in the kernel breaks this principle.

Here is a demonstration using Conda to create two environments, one called jupyter-env in which jupyter notebook is run, and one called black-env which contains the python kernel (ipykernel) and (unfortunately) needs to have black installed:

# Create the black-env with ipykernel and black
conda create -y -n black-env ipykernel
conda activate black-env
python3 -m pip install black

# This installs the kernel globally so it can be selected.  Look at the output to see where so you
# can remove it later.
python3 -m ipykernel install --user --name "black-env" --display-name "Python 3 (black-env)"
conda deactivate

# Now create the jupyter-env which will run jupyter.  I will install the configurator here
# so that I can use this to enable the black extension.  Note: I do not need to install
# black in this environment.
conda create -y -n jupyter-env python
python3 -m pip install jupyter notebook "jupyter-nbextensions-configurator>=0.6.3"

# Now try creating a notebook, setting the kernel to "black-env" which should appear
# in the list of kernels, enable the black extension in the nbextension tab, and format
# a cell.
conda activate jupyter-env
jupyter notebook

There are two possible resolutions here:

  1. Document the current behaviour, that black is needed in the kernel.
  2. Change the behaviour so that black is only needed in the environment running jupyter. This might be hard/impossible given how cell formatting is implemented though, but would be very nice.

Outlook integration

Would be really useful to have a Outlook integration. The outlook.js does not seem to work. At least not for the most recent outlook. I was able to get something with the following additions:

integrations.json:

	"outlook.office365.com": {
		"name": "Outlook Mail",
		"link": "*://outlook.office365.com/*",
		"script": "outlook-mail.js"
	},

outlook-mail.js:

// Inbox emails
clockifyButton.render(
	'div[class="MByod XxeQL"]:not(.clockify)',
	{ observe: true },
	function (elem) {
		const description = $('[aria-label="Reading Pane"] [role="heading"]')
		link = clockifyButton.createButton(description.textContent);
		link.style.marginLeft = '20px';
		link.style.fontSize = '14px';
		elem.appendChild(link);
	}
);

This is not pretty but worked for me. I imagine 'div[class="MByod XxeQL"]:not(.clockify)' is not the best, seems like this could change?

I imagine one of you guys could implement a better solution within minutes. I would appreciate that and I am sure many others would to!

Extension broken when autotime is loaded

Hey,

I'm quite extensively using autotime to print out the execution time of the cells (I think it's built-in into juptyer these days?). After the autotime extension is loaded with %load_ext autotime, no cells can be auto-formatted using jupyter-black, all attempts result in an error like SyntaxError: Unexpected token t in JSON at position 40. (the exact position can change). Restarting the kernel, and therefore unloading the autotime extension makes the jupyter-black extension to work again.

Minimal example:

%load_ext autotime
print('test')

It's possible to reformat this before running the cell, but not after running it. Please advise?

Skip jupyter magic lines

I have a cell that has jupyter magic in it.

%%time
# Stuff to time
a = 1

Currently black fails it is not valid python.

black extension
 Error: InvalidInput
Cannot parse: 1:0: %%time

I can get around this by temporarily commenting out the line when running black but would it be possible to just skip these magic lines?

How to install it in Jupyter Lab?

I tried installing this with the commands you wrote:
jupyter nbextension install https://github.com/drillan/jupyter-black/archive/master.zip --user jupyter nbextension enable jupyter-black-master/jupyter-black

But it's not working in Jupyter Lab...

Perhaps set the black line length to the width of the text box

There's a discussion of PEP 8 on the Python ideas list. I suggest there that one might use black.py to 'line-wrap' the Python code to what is the current width of the editor window.

Hence my suggestion, that it be possible to set the black line length to the width of the text box.

https://mail.python.org/pipermail/python-ideas/2019-February/055359.html # Start of thread.
https://mail.python.org/pipermail/python-ideas/2019-February/055424.html # My post on jupyter-black.

TypeError when trying to format with black

Hi,

Thanks for this extension. However, I can't use it because it always throws this error in my face:

Bildschirmfoto_2019-12-04_09-59-14

This happens in an existing notebook, in a fresh notebook, from the button and via the CTRL-B keyboard shortcut.

Running the notebook with --log-level=DEBUG only shows these 4 lines when the error occurs:

[D 10:12:42.912 NotebookApp] activity on ffbe4112-f925-46b3-91a4-5e09801c2865: status
[D 10:12:42.914 NotebookApp] activity on ffbe4112-f925-46b3-91a4-5e09801c2865: execute_input
[D 10:12:42.928 NotebookApp] activity on ffbe4112-f925-46b3-91a4-5e09801c2865: error
[D 10:12:42.931 NotebookApp] activity on ffbe4112-f925-46b3-91a4-5e09801c2865: status

My environment:

> lsb_release -a
Distributor ID:	Ubuntu
Description:	Ubuntu 18.04.3 LTS
Release:	18.04
Codename:	bionic
> firefox -v
Mozilla Firefox 70.0.1
> vivaldi --version
Vivaldi 1.15.1147.64
> python3 -V
Python 3.6.9
> pip3 show black
Name: black
Version: 18.9b0
Summary: The uncompromising code formatter.
Home-page: https://github.com/ambv/black
Author: Łukasz Langa
Author-email: [email protected]
License: MIT
Location: /home/yann/.local/lib/python3.6/site-packages
Requires: click, appdirs, attrs, toml
Required-by: clean-ipynb
> pip3 show jupyter_contrib_nbextensions
Name: jupyter-contrib-nbextensions
Version: 0.5.1
Summary: A collection of Jupyter nbextensions.
Home-page: https://github.com/ipython-contrib/jupyter_contrib_nbextensions.git
Author: ipython-contrib and jupyter-contrib developers
Author-email: [email protected]
License: BSD
Location: /home/yann/.local/lib/python3.6/site-packages
Requires: traitlets, nbconvert, notebook, ipython-genutils, jupyter-nbextensions-configurator, jupyter-contrib-core, jupyter-core, pyyaml, tornado, jupyter-highlight-selected-word, lxml, jupyter-latex-envs
Required-by: 

I previously installed the extension manually as instructed in the README. Same error.

I might just be blind.

Any ideas?

No module named 'platformdirs'

One time I installed jupyter-black & it worked without any problems.
Today I got the next message when I tried to use it:

[jupyter-black]
Error: ModuleNotFoundError
No module named 'platformdirs'

This is shown only one time. After that jupyter shows:

[jupyter-black]
Error: AttributeError
module 'black' has no attribute 'FileMode'

I have platformdirs installed. At least pip show its existence & the latest version. What could go wrong?
Goggling gave me nothing relevant with black & Jupyter

Black type error

First time using jupyter-black after installation I get a popup with.

black extension
 Error: TypeError
format_str() takes 1 positional argument but 2 were given

Python 3.6.6
black-19.3b0

Extension does not load: undefined is not an object (evaluating 'action.help')

First of all, thanks for this extension, I found it very useful in my work!

I upgraded python → 3.8 and jupyter and currently cannot load jupyter-black extension if toolbar button is enabled. In javascript console I have the following error message:

[jupyter-black] – "error loading:"
TypeError: undefined is not an object (evaluating 'action.help') — toolbar.js:98
on_error — kernel_exec_on_cell.js:352
promiseReactionJob
toolbar.js:98

The corresponding source code:

                var button  = $('<button/>')
                    .addClass('btn btn-default')
                    .attr("aria-label", el.label)
                    .attr("title", i18n.msg._(action.help)||el.label)
                    .append(
                        $("<i/>").addClass(el.icon||(action||{icon:'fa-exclamation-triangle'}).icon).addClass('fa')
                    );

If I disable toolbar button, extension is loaded and working with hotkey.

InvalidInput Error

[jupyter-black]
 Error: InvalidInput
Cannot parse: 5:0: temp_graph = erdos_renyi_graph(4, 0.7, 0, directed = False)

While reformatting the cell:

class GraphGenerator():
    def __init__(self, number_of_nodes =200):
    

temp_graph = erdos_renyi_graph(4, 0.7, 0, directed = False)
nx.draw(temp_graph)

installation

What do you mean by this?

If you use jupyter-contrib-nbextensions, proceed as usual.

Could you spell out those steps, please?

Black freezes on this cell example with leading spaces in the cell

Using Jupyter Notebook in Firefox 53.0.2 on windows 7, Black freezes when I press Ctrl-l to format a cell with leading spaces.

Example:

Cell 1
print('hello')

Cell 2
[4x times Space]for a in range(10):
[8x times Space]print(a)

Pressing Ctrl-l in Cell 1 changes the code to
print("hello")

Pressing Ctrl-l in Cell 2 freezes the notebook and I
need to kill the tab. Without leading spaces on the first line,
Cell 2 formats fine.

Bare await statements

Jupyter allows for bare await statements in a cell, e.g.

async def f():
    pass

await f()

However, jupyter-black doesn't like it:

Cannot parse: 4:6: await f()

Skip Jupyter system lines

Similar to #5, this currently fails on cells with a system command:

!pip install numpy

These lines could be skipped in the same way.

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.