Note

Go to the endto download the full example code or to run this example in your browser via JupyterLite or Binder.

Identifying function names in a script#

This demonstrates how Sphinx-Gallery identifies when

  1. a function/method/attribute/object is used or class instantiated in acode block

  2. a function/method/attribute/object/class is referred to using sphinx markupin a text block.

Sphinx-Gallery examines both the executed code itself, as well as thetext blocks (such as this one, or the one below) for these references andidentifies the module they belong to. This means that by writingnumpy.sin andnumpy.exp here, they will be identified even thoughthey are not used in the code. This is useful in particular when functionsreturn classes (meaning it is not explicitly instantiated) – if you add themto the documented blocks of examples that use them, they will be added tobackreferences.

This functionality is used to add documentation hyperlinks to your code(Add intersphinx links to your examples) and for mini-gallery creation(Add mini-galleries for API documentation).

# Code source: Óscar Nájera# License: BSD 3 clauseimportos.pathasop# noqa, analysis:ignoreimportmatplotlib.pyplotaspltimportsphinx_galleryfromsphinx_gallery.backreferencesimport_make_ref_regex,identify_namesfromsphinx_gallery.py_source_parserimportsplit_code_and_text_blocksfilename="plot_6_function_identifier.py"ifnotop.exists(filename):filename=(__file__if"__file__"inlocals()elseop.join(op.dirname(sphinx_gallery.__path__[0]),"examples",filename))_,script_blocks=split_code_and_text_blocks(filename)names=identify_names(script_blocks,_make_ref_regex())

In the code block above, we use the internal functionidentify_names toobtain all identified names from this file and their full resolved importpath. We then plot this below, where the identified names functions areon the left and the full resolved import path is on the right.

fontsize=12.5figheight=3*len(names)*fontsize/72fig,ax=plt.subplots(figsize=(7.5,figheight))ax.set_visible(False)fori,(name,obj)inenumerate(names.items(),1):fig.text(0.48,1-i/(len(names)+1),name,ha="right",va="center",size=fontsize,transform=fig.transFigure,bbox=dict(boxstyle="square",fc="w",ec="k"),)fig.text(0.52,1-i/(len(names)+1),obj[0]["module"],ha="left",va="center",size=fontsize,transform=fig.transFigure,bbox=dict(boxstyle="larrow,pad=0.1",fc="w",ec="k"),)plt.show()
plot 6 function identifier

Total running time of the script: (0 minutes 0.875 seconds)

Estimated memory usage: 220 MB

Gallery generated by Sphinx-Gallery