return a**2 Note that to create a docstring for our function,we simply placed a string literal in the first line.Because docstrings are usually multiple lines,by convention we used Now we'll use the mark to find this docstring: In [7]:square? function String form:<function square at 0x103713cb0> square(a Return the square of a. This quick access to documentation via docstrings is one reason you should get in the habit of always adding such inline documentation to the code you write! Accessing Source Code with ? Because the Python language is so easily readable,you can usually gain another leve of insight by reading the source code of the object you're curious about.IPython pro- vides a shortcut to the source code with the double question mark(??): String form:<function square at 0x103713cb0> Definition:square(a) For simple functions like this,the double question mark can give quick insight into the under-the-hood details If you play with this much,you'll notice that sometimes the ?suffix doesn't display any source code:this is generally because the object in question is not implemented in Python,but in C or some other compiled extension language.If this is the case,the ? suffix gives the same output as the suffix.You'll find this particularly with many of Python's built-in objects and types,for example len from above: In [91:len?? builtin_function_or_method String form:<built-in function len> Python builtin Return the number of items of a sequence or mapping. Help and Documentation in IPython 5
....: return a ** 2 ....: Note that to create a docstring for our function, we simply placed a string literal in the first line. Because docstrings are usually multiple lines, by convention we used Python’s triple-quote notation for multiline strings. Now we’ll use the ? mark to find this docstring: In [7]: square? Type: function String form: <function square at 0x103713cb0> Definition: square(a) Docstring: Return the square of a. This quick access to documentation via docstrings is one reason you should get in the habit of always adding such inline documentation to the code you write! Accessing Source Code with ?? Because the Python language is so easily readable, you can usually gain another level of insight by reading the source code of the object you’re curious about. IPython pro‐ vides a shortcut to the source code with the double question mark (??): In [8]: square?? Type: function String form: <function square at 0x103713cb0> Definition: square(a) Source: def square(a): "Return the square of a" return a ** 2 For simple functions like this, the double question mark can give quick insight into the under-the-hood details. If you play with this much, you’ll notice that sometimes the ?? suffix doesn’t display any source code: this is generally because the object in question is not implemented in Python, but in C or some other compiled extension language. If this is the case, the ?? suffix gives the same output as the ? suffix. You’ll find this particularly with many of Python’s built-in objects and types, for example len from above: In [9]: len?? Type: builtin_function_or_method String form: <built-in function len> Namespace: Python builtin Docstring: len(object) -> integer Return the number of items of a sequence or mapping. Help and Documentation in IPython | 5
Using and/or ?gives a powerful and quick interface for finding information about what any Python function or module does. Exploring Modules with Tab Completion IPython's other useful interface is the use of the Tab key for autocompletion and exploration of the contents of objects,modules,and namespaces.In the examples that follow,we'll use <TAB>to indicate when the Tab key should be pressed. Tab completion of object contents Every Python object has various attributes and methods associated with it.Like with the help function discussed before,Python has a built-in dir function that returns a list of these,but the tab-completio n inte erface is much easier touse in practice.To alist of all available attributes of an object,you can type the name of the object fol- lowed by a period(.)character and the Tab key: In [101: I append I copy L.extend L.insert L.remove L.sort L.clear L.count L.index L.pop L.reverse To narrow down the list,you can type the first character or several characters of the name,and the Tab key will find the matching attributes and methods: In [1]:L.co<TAB> L.copy L.count If there is only a single option,pressing the Tab key will complete the line for you.For example,the following will instantly be replaced with L.count: In [10]:L.cou<TAB> Though Python has no strictly enforced distinction between public/external receding underscore is A used to denote such ethods.For cla rity,these pri methods are omitted from the list by default,but it's possible to list them by explicitly typing the underscore: In [10]:L._<TAB> L.add L.gt L.reduce L.class L.hash L.reduce ex For brevity,we've only shown the first couple lines of the output.Most of these are Python's special double-underscore methods(often nicknamed"dunder"methods). 6Chapter 1:IPython:Beyond Normal Python
Using ? and/or ?? gives a powerful and quick interface for finding information about what any Python function or module does. Exploring Modules with Tab Completion IPython’s other useful interface is the use of the Tab key for autocompletion and exploration of the contents of objects, modules, and namespaces. In the examples that follow, we’ll use <TAB> to indicate when the Tab key should be pressed. Tab completion of object contents Every Python object has various attributes and methods associated with it. Like with the help function discussed before, Python has a built-in dir function that returns a list of these, but the tab-completion interface is much easier to use in practice. To see a list of all available attributes of an object, you can type the name of the object fol‐ lowed by a period (.) character and the Tab key: In [10]: L.<TAB> L.append L.copy L.extend L.insert L.remove L.sort L.clear L.count L.index L.pop L.reverse To narrow down the list, you can type the first character or several characters of the name, and the Tab key will find the matching attributes and methods: In [10]: L.c<TAB> L.clear L.copy L.count In [10]: L.co<TAB> L.copy L.count If there is only a single option, pressing the Tab key will complete the line for you. For example, the following will instantly be replaced with L.count: In [10]: L.cou<TAB> Though Python has no strictly enforced distinction between public/external attributes and private/internal attributes, by convention a preceding underscore is used to denote such methods. For clarity, these private methods and special methods are omitted from the list by default, but it’s possible to list them by explicitly typing the underscore: In [10]: L._<TAB> L.__add__ L.__gt__ L.__reduce__ L.__class__ L.__hash__ L.__reduce_ex__ For brevity, we’ve only shown the first couple lines of the output. Most of these are Python’s special double-underscore methods (often nicknamed “dunder” methods). 6 | Chapter 1: IPython: Beyond Normal Python
Tab completion when importing Tab completion is also useful when importing objects from packages.Here we'll use it to find all possible imports in the itertools package that start with co: In [10] fron itertools import coTAB Similarly,you can use tab completion to see which imports are available on your sys- tem(this will change depending on which third-party scripts and modules are visible to your Python session): In [10]:import <TAB> Display all 399 possibilities?(y or n) difflib pwd zna nport hT html (Note that for brevity,I did not print here all 399 importable packages and modules on my system.) Beyond tab completion:Wildcard matching Tab completion is useful if you know the first few characters of the object or attribute you're looking for,but is little help if you'd like to match characters at the middle or end of the word.For this use case,IPython provides a means of wildcard matching for names using the*character. For example,we can use this to list every object in the namespace that ends with Warning: *Warning? Deprcatio arning Futurewarning UnicodeWarning ecationWarning esourceWarning Notice that the*character matches any string,including the empty string. Similarly,suppose we are looking for a string method that contains the word find somewhere in its name.We can search for it this way: Help and Documentation in IPython 7
Tab completion when importing Tab completion is also useful when importing objects from packages. Here we’ll use it to find all possible imports in the itertools package that start with co: In [10]: from itertools import co<TAB> combinations compress combinations_with_replacement count Similarly, you can use tab completion to see which imports are available on your sys‐ tem (this will change depending on which third-party scripts and modules are visible to your Python session): In [10]: import <TAB> Display all 399 possibilities? (y or n) Crypto dis py_compile Cython distutils pyclbr ... ... ... difflib pwd zmq In [10]: import h<TAB> hashlib hmac http heapq html husl (Note that for brevity, I did not print here all 399 importable packages and modules on my system.) Beyond tab completion: Wildcard matching Tab completion is useful if you know the first few characters of the object or attribute you’re looking for, but is little help if you’d like to match characters at the middle or end of the word. For this use case, IPython provides a means of wildcard matching for names using the * character. For example, we can use this to list every object in the namespace that ends with Warning: In [10]: *Warning? BytesWarning RuntimeWarning DeprecationWarning SyntaxWarning FutureWarning UnicodeWarning ImportWarning UserWarning PendingDeprecationWarning Warning ResourceWarning Notice that the * character matches any string, including the empty string. Similarly, suppose we are looking for a string method that contains the word find somewhere in its name. We can search for it this way: Help and Documentation in IPython | 7
In [10]:str.*find*? str.find str.rfind I find this type of flexible wildcard search can be very useful for finding a particular command when I'm getting to know a new package or reacquainting myself with a familiar one Keyboard Shortcuts in the IPython Shell If you spend any amount of time on the computer,you've probably found a use for keybo your workflow.Most fan thaps are Cmd-C and Cmd-V (or Ctrl-C and Ctrl-V)for copying and pasting in a wide variety of programs and sys- tems.Power users tend to go even further:popular text editors like Emacs,Vim,and others provide users an incredible range of operations through intricate combina tions of keystrokes The IPython shell doesn't go this far,but does provide a number of keyboard short- cuts for fast navigation while you're typing commands.These shortcuts are not in fact oyded by IPython itsel but through its dependency on the GN Readline bra of the following shortc ts may differ de pend: ng on your system n con ration.Also,while some of these shortcuts do work in the browser-based notebook this section is primarily about shortcuts in the IPython shell. Once you get accustomed to these,they can be very useful for quickly performing certain ands with out r moving your hands fron the "h ome" ar If you're an Emacs user or if you have experience with Linux-style shells,the follow ing will be very familiar.We'll group these shortcuts into a few categories:navigation shortcuts,text entry shortcuts,command history shortcuts,and miscellaneous shortcuts. Navigation Shortcuts While the use of the left and right arrow keys to move backward and forward in the line is quite obvious,there are other options that don't require moving your hands from the"home"keyboard position: Keystroke Action Ctrl-a Move cursor to the beginning of the line Ctrle Move cursor to the end of the line Ctr-b(or the left arow key) Ctrl-f(or the right arrow key)Move cursor forward one character 8Chapter 1:IPython:Beyond Normal Python
In [10]: str.*find*? str.find str.rfind I find this type of flexible wildcard search can be very useful for finding a particular command when I’m getting to know a new package or reacquainting myself with a familiar one. Keyboard Shortcuts in the IPython Shell If you spend any amount of time on the computer, you’ve probably found a use for keyboard shortcuts in your workflow. Most familiar perhaps are Cmd-C and Cmd-V (or Ctrl-C and Ctrl-V) for copying and pasting in a wide variety of programs and sys‐ tems. Power users tend to go even further: popular text editors like Emacs, Vim, and others provide users an incredible range of operations through intricate combina‐ tions of keystrokes. The IPython shell doesn’t go this far, but does provide a number of keyboard short‐ cuts for fast navigation while you’re typing commands. These shortcuts are not in fact provided by IPython itself, but through its dependency on the GNU Readline library: thus, some of the following shortcuts may differ depending on your system configu‐ ration. Also, while some of these shortcuts do work in the browser-based notebook, this section is primarily about shortcuts in the IPython shell. Once you get accustomed to these, they can be very useful for quickly performing certain commands without moving your hands from the “home” keyboard position. If you’re an Emacs user or if you have experience with Linux-style shells, the follow‐ ing will be very familiar. We’ll group these shortcuts into a few categories: navigation shortcuts, text entry shortcuts, command history shortcuts, and miscellaneous shortcuts. Navigation Shortcuts While the use of the left and right arrow keys to move backward and forward in the line is quite obvious, there are other options that don’t require moving your hands from the “home” keyboard position: Keystroke Action Ctrl-a Move cursor to the beginning of the line Ctrl-e Move cursor to the end of the line Ctrl-b (or the left arrow key) Move cursor back one character Ctrl-f (or the right arrow key) Move cursor forward one character 8 | Chapter 1: IPython: Beyond Normal Python
Text Entry Shortcuts While everyone is familiar with using the Backspace key to delete the previous char acter,reaching for the key often requires some minor finger gymnastics,and it only deletes a single character at a time.In IPython there are several shortcuts for remov ing some ortion of the text youre typing.The most imm ediately useful of these ar the commands to delete entire lines of text.You'll know these have become second nature if you find yourself using a combination of Ctrl-b and Ctrl-d instead of reach- ing for the Backspace key to delete the previous character! Keystroke Action Badkspace key Delete previous character in line Ctrl-d Delete next characterinin Ctrl-k Cut text from cursor to end of line Ctrl-u Cut text from begining foine to cursor Ctrl-y Yank (i.e..paste)text that was previously cut Crl-t Transpose ()previous two characters Command History Shortcuts Perhaps the most impactful shortcuts discussed here are the ones IPython provides for navigating the command history.This command history goes beyond your cur- rent IPython session our entire command history is stored in a SQLite database in your IPython profile directory.The most straightforward way to access these is with the up and down arrow keys to step through the history,but other options exist as well: Keystroke Action Ctrl-p (or the up arrow key)Access previous command in history (or thedown arow key) Access next command in history c Reverse-search through command history The reverse-search can be particularly useful.Recall that in the previous section we defined a function called square.Let's reverse-search our Python history from a new IPython shell and find this definition again.When you press Ctrl-r in the IPython terminal,you'll see the e following prompt (reverse-i-search)'' If you start typing characters at this prompt IPython will auto-fil the most recen command,if any,that matches those characters: Keyboard Shortcuts in the IPython Shell9
Text Entry Shortcuts While everyone is familiar with using the Backspace key to delete the previous char‐ acter, reaching for the key often requires some minor finger gymnastics, and it only deletes a single character at a time. In IPython there are several shortcuts for remov‐ ing some portion of the text you’re typing. The most immediately useful of these are the commands to delete entire lines of text. You’ll know these have become second nature if you find yourself using a combination of Ctrl-b and Ctrl-d instead of reach‐ ing for the Backspace key to delete the previous character! Keystroke Action Backspace key Delete previous character in line Ctrl-d Delete next character in line Ctrl-k Cut text from cursor to end of line Ctrl-u Cut text from beginning fo line to cursor Ctrl-y Yank (i.e., paste) text that was previously cut Ctrl-t Transpose (i.e., switch) previous two characters Command History Shortcuts Perhaps the most impactful shortcuts discussed here are the ones IPython provides for navigating the command history. This command history goes beyond your cur‐ rent IPython session: your entire command history is stored in a SQLite database in your IPython profile directory. The most straightforward way to access these is with the up and down arrow keys to step through the history, but other options exist as well: Keystroke Action Ctrl-p (or the up arrow key) Access previous command in history Ctrl-n (or the down arrow key) Access next command in history Ctrl-r Reverse-search through command history The reverse-search can be particularly useful. Recall that in the previous section we defined a function called square. Let’s reverse-search our Python history from a new IPython shell and find this definition again. When you press Ctrl-r in the IPython terminal, you’ll see the following prompt: In [1]: (reverse-i-search)`': If you start typing characters at this prompt, IPython will auto-fill the most recent command, if any, that matches those characters: Keyboard Shortcuts in the IPython Shell | 9