Python users who work in Jupyter computational notebooks have access to an extra collection of commands, known as magic commands. Magic commands are an enhancement of the interactive IPython kernel (used by Jupyter) and make performing common tasks easier than using Python code alone.
Line magics and cell magics
Magic commands are easily identified because they all start with the % character. Line magics start with a single % and apply to the code on the rest of the line. Cell magics start with %% and apply to the rest of the code in a cell.
Below is a list of some of the built-in magic commands that I have found most useful. As with all Python functionality, more magic commands can be accessed from user-contributed packages.
How fast is your code?
Measuring execution time can help you optimise the performance of your code. Use the magic command %timeit (written at the beginning of a line of code) to return the time it takes to run that line of code. For multiple lines of code, use %%timeit.
Which is faster, a list comprehension or a for loop?
Autocomplete not working (especially with pandas)?
Often the solution is to simply disable the Jedi library autocomplete:
Write your code to a file
Want to save code in a notebook cell to a .py file? Use the %%writefile magic command. This is a great way to save custom functions into a file for reuse later.
Reload code from a file
Code can be loaded into a Notebook cell from a .py file using %load.
When the code is run, the lines below the magic command will contain the code from the file.
Want to see variables you’ve created?
The %who magic commands return the variables in various forms and can be used to return specific types of variables.
For more information on the built-in magic commands check out the IPython documentation.
Learn more about Python check out our Python Training Courses. Use the skills test to determine where you sit and then book into our basics, data analysis in python, and python intermediate. We also offer python certification. Available in person in our CBD locations or remote online across Australia.