Rock It 《ML》JupyterLab 【丁】Code《七》語義【二】補篇

認識一棵『樹』

Tree (data structure)

A simple unordered tree; in this diagram, the node labeled 7 has two children, labeled 2 and 6, and one parent, labeled 2. The root node, at the top, has no parent.

In computer science, a tree is a widely used abstract data type (ADT)—or data structure implementing this ADT—that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent node, represented as a set of linked nodes.

A tree data structure can be defined recursively as a collection of nodes (starting at a root node), where each node is a data structure consisting of a value, together with a list of references to nodes (the “children”), with the constraints that no reference is duplicated, and none points to the root.

Alternatively, a tree can be defined abstractly as a whole (globally) as an ordered tree, with a value assigned to each node. Both these perspectives are useful: while a tree can be analyzed mathematically as a whole, when actually represented as a data structure it is usually represented and worked with separately by node (rather than as a set of nodes and an adjacency list of edges between nodes, as one may represent a digraph, for instance). For example, looking at a tree as a whole, one can talk about “the parent node” of a given node, but in general as a data structure a given node only contains the list of its children, but does not contain a reference to its parent (if any).

 

始於知道『節點』是什麼,與之相逢︰

Meet the Nodes

An AST represents each element in your code as an object. These are instances of the various subclasses of AST described below. For instance, the code a + 1 is a BinOp, with a Name on the left, a Num on the right, and an Add operator.

………

固可藉圖示,一目了然!

 

仍需知其內封裝的『數據』乎?

 

不過這個 ast.dump 之輸出,不易讀也☻

所以 Green Tree Snakes 才選用 parseprint 漂亮列印吧☺

classJoinedStr(values)

New in version 3.6.

An f-string, comprising a series of FormattedValue and Str nodes.

>>> parseprint('f"sin({a}) is {sin(a):.3}"')
Module(body=[
    Expr(value=JoinedStr(values=[
        Str(s='sin('),
        FormattedValue(value=Name(id='a', ctx=Load()), conversion=-1, format_spec=None),
        Str(s=') is '),
        FormattedValue(value=Call(func=Name(id='sin', ctx=Load()), args=[
            Name(id='a', ctx=Load()),
          ], keywords=[]), conversion=-1, format_spec=JoinedStr(values=[
            Str(s='.3'),
          ])),
      ])),
  ])

Note

The pretty-printer used in these examples is available in the source repository for Green Tree Snakes.

※ 註︰

 
examples
40 B
 
5.6 KB
 
173 B
 
3.3 KB
 
173 B
 
8.0 KB
 
4.0 KB
 
1.4 KB
 
5.1 KB
 
3.5 KB
 
30.5 KB
 
2.8 KB
 
This is the source repository for Green Tree Snakes, a field guide to Abstract Syntax Trees in Python.

 

讀過原始碼後,心想既未打包成套件,何不介紹直用之法哩︰

【依樣葫蘆】

 

【直接引用】

 

順道講點 IPython 『魔術』奧秘︰

Defining custom magics

There are two main ways to define your own magic functions: from standalone functions and by inheriting from a base class provided by IPython: IPython.core.magic.Magics. Below we show code you can place in a file that you load from your configuration, such as any file in the startupsubdirectory of your default IPython profile.

First, let us see the simplest case. The following shows how to create a line magic, a cell one and one that works in both modes, using just plain functions:

from IPython.core.magic import (register_line_magic, register_cell_magic,
                                register_line_cell_magic)

@register_line_magic
def lmagic(line):
    "my line magic"
    return line

@register_cell_magic
def cmagic(line, cell):
    "my cell magic"
    return line, cell

@register_line_cell_magic
def lcmagic(line, cell=None):
    "Magic that works both as %lcmagic and as %%lcmagic"
    if cell is None:
        print("Called as line magic")
        return line
    else:
        print("Called as cell magic")
        return line, cell

# In an interactive session, we need to delete these to avoid
# name conflicts for automagic to work on line magics.
del lmagic, lcmagic

※ 出自︰

1.4. Creating an IPython extension with custom magic commands

IPython Cookbook, Second EditionThis is one of the 100+ free recipes of the IPython Cookbook, Second Edition, by Cyrille Rossant, a guide to numerical computing and data science in the Jupyter Notebook. The ebook and printed book are available for purchase at Packt Publishing.

▶  Text on GitHub with a CC-BY-NC-ND license
▶  Code on GitHub with a MIT license

▶  Go to Chapter 1 : A Tour of Interactive Computing with Jupyter and IPython
▶  Get the Jupyter notebook

Although IPython comes with a wide variety of magic commands, there are cases where we need to implement custom functionality in new magic commands. In this recipe, we will show how to create line and magic cells, and how to integrate them in an IPython extension.

 

以饗讀者呦☆