3-3-1-9. Magic Keywords

Magic Keywords

Magic keywords are special commands you can run in cells that let you control the notebook itself or perform system calls such as changing directories. For example, you can set up matplotlib to work interactively in the notebook with Magic commands are preceded with one or two percent signs (NOTE: These magic keywords are specific to the normal Python kernel. If you are using other kernels, these most likely won’t work.

Timing code

At some point, you’ll probably spend some effort optimizing code to run faster. Timing how quickly your code runs is essential for this optimization. You can use the timeit magic command to time how long it takes for a function to run, like so:

Embedding visualizations in notebooks

As mentioned before, notebooks let you embed images along with text and code. This is most useful when you’re using matplotlib or other plotting packages to create visualizations. You can use 

Tip: On higher resolution screens such as Retina displays, the default images in notebooks can look blurry. Use 

Debugging in the Notebook

With the Python kernel, you can turn on the interactive debugger using the magic command 

Above you can see I tried to sum up a string which gives an error. The debugger raises the error and provides a prompt for inspecting your code.

Read more about pdb in the documentation. To quit the debugger, simply enter q in the prompt.

More reading

There are a whole bunch of other magic commands, I just touched on a few of the ones you’ll use the most often. To learn more about them, here’s the list of all available magic commands.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading