Where to put import statements in a jupyter notebook - ipython

I realized that I am not too sure of where to put my import statements in a exploratory jupyter notebook.
I am currently putting all my imports in a notebook together in a cell in the beginning. Is this proper style?

Related

VS Code code folding of Python code in Jupyter Notebooks?

I'm looking to fold code in Jupyter Notebook cells.
Note this is different from folding the whole cell or the whole output.
This illustrates the feature well (it's a Gif):
Is there any way to achieve this in VS Code?

How do I edit a jupyter notebook cell's tags in visual studio code?

I am editing a .ipynb file in Visual Studio Code, with the file open in VS code's Jupyter Notebook editor.
When I edit this notebook in the Jupyter Notebook App (i.e. if I were not using VS code, instead using the interface described here), I could add tags to cells by clicking View > Cell Toolbar > Tags, and then entering tags into the UI that comes up.
Is there an equivalent way to do this in VS Code?
I am aware I can reopen the file in a text editor view and edit the JSON directly. But I am looking for something a bit more user friendly than this.
Try installing this jupyter on vs code.
On my old windows 7 I used to use this. It has the same interface as when you open Jupiter in your browser but you don't need to load a bunch of stuff to open jupyter. You can open it in one single click like changing text file while writing code inside vc code.
Also you need to install one library to use it but unfortunately I can't remember the library as I don't use python or Jupiter anymore.
In the documentation is a python code cell which enables to change all the cell tags.
import nbformat as nbf
from glob import glob
# Collect a list of all notebooks in the content folder
notebooks = glob("**/*.ipynb", recursive=True)
notebooks_windows = []
for i in notebooks:
j = i.replace("\\", "/")
notebooks_windows.append(j)
notebooks_windows
# Text to look for in adding tags
text_search_dict = {
"# HIDDEN": "remove-cell", # Remove the whole cell
"# NO CODE": "remove-input", # Remove only the input
"# HIDE CODE": "hide-input" # Hide the input w/ a button to show
}
# Search through each notebook and look for the text, add a tag if necessary
for ipath in notebooks_windows:
ntbk = nbf.read(ipath, nbf.NO_CONVERT)
for cell in ntbk.cells:
cell_tags = cell.get('metadata', {}).get('tags', [])
for key, val in text_search_dict.items():
if key in cell['source']:
if val not in cell_tags:
cell_tags.append(val)
if len(cell_tags) > 0:
cell['metadata']['tags'] = cell_tags
Microsoft have finally released an extra extension to support this.
ms-toolsai.vscode-jupyter-cell-tags
See this long running github.com/microsoft/vscode-jupyter issue #1182 and comment recently closing the issue.
Be ware however, that while you can set tags, e.g. raises-exception, which is meant to make the runtime expect and ignore the exception and keep on running more cells, but the vscode-jupyter extension that runs the cells does not always honor tag features the same way that the standard Jupyter notebook runtime does, and so, disappointingly, it's still difficult to demo common mistakes or what not to do (exceptions).
Just copy everything in .py file with the unremovable tags, paste that into a plaintext file. The tags are now just editable text. Remove them, Save As or copy/paste back to the .py file.

How does the code in Jupyter Notebook get executed in Ipython

I am new to jupyter and I modify the html content of the generated notebook when you click create new Notebook in Jupyter. I have added an html block that contains a jupyter code to display graph or markdown code. Now, does anybody know how do I use the jupyter javascripts to interpret my code and display it inside the jupyter notebook cell index 0?. If my question is not clear please let me know and would love to edit it.
currently, I see this code in jupyter main.min.js. But how do they get the code and send it to python.
'run-cell':{
help : 'run selected cells',
help_index : 'bb',
handler : function (env) {
env.notebook.execute_selected_cells();
}
},

Can I create an iPython notebook using JavaScript as the language in the cells?

I love IPython to explain algorithms in python. But I want to do the same using javascript. Is it possible to write a notebook where I use javascript as the cell language?
You can use the %%javascript magic function for running javascript in IPython notebook. For example Paste the following code in a IPython cell and run it. You should see the output in your browser's javascript console.
%%javascript
console.log("Hello World!")
For global variables, you can add an attribute to the windows object for
example, in a cell run the following code:
%%javascript
window.myvar = 12;
In another cell, run the following code and check browser's javascript console. The variable's value should be printed.
%%javascript
console.log(myvar)
Use the element variable for printing in the cell output area as shown below:
%%javascript
element.append(myvar)

How to show (as output cell) the contents of a .py file with syntax highlighting?

I'm aware of the %load function (formerly %loadpy) which loads the contents of a file (or URL, ...) into a new input cell (which can be executed afterwards).
I'm also aware of %less, %more and %pycat, which show the contents of a file in a pager (which means in the notebook it's shown in the split-window at the bottom of the screen).
Is there a (magic) command to load a file and show its content (with syntax highlighting) in an output cell?
I.e. something like the following but with syntax highlighting of the result:
with open('my_file.py', 'r') as f:
print(f.read())
I want the file content to be stored with the .ipynb file but I don't want it to be executed when I do Cell -> Run All.
Is there a command similar to %psource which shows the source code in an output cell instead of a pager?
Example code based on answer by #Matt:
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
import IPython
with open('my_file.py') as f:
code = f.read()
formatter = HtmlFormatter()
IPython.display.HTML('<style type="text/css">{}</style>{}'.format(
formatter.get_style_defs('.highlight'),
highlight(code, PythonLexer(), formatter)))
No there is not way to do that with current magics, but it is pretty easy using pygments and returning IPython.display.HTML(...).
10 years later, and there's now a much simpler solution:
https://ipython.readthedocs.io/en/stable/api/generated/IPython.display.html#IPython.display.Code
from IPython.display import Code
Code(filename='my_file.py', language='python')