Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Are your examples real code, or just examples?</p> <p>If they're real code, I think you overuse decorators, probably because of your background (i.e. you are used to other programming languages)</p> <h3>Stage 1: avoiding decorators</h3> <pre><code>def run(rootnode, func): def _run(node): # recursive internal function func(node) for x in node.children: _run(x) # recurse _run(rootnode) # initial run </code></pre> <p>This run method obsoletes makeRunner. Your example turns to:</p> <pre><code>def pp(n): print "%s," % n.val run(tree, pp) </code></pre> <p>However, this ignores completely generators, so…</p> <h3>Stage 2: using generators</h3> <pre><code>class Node : def __init__(self,val,children) : self.val = val self.children = children def __iter__(self): # recursive yield self for child in self.children: for item in child: # recurse yield item def run(rootnode, func): for node in rootnode: func(node) </code></pre> <p>Your example remains</p> <pre><code>def pp(n): print "%s," % n.val run(tree, pp) </code></pre> <p>Note that the special method <code>__iter__</code> allows us to use the <code>for node in rootnode:</code> construct. If you don't like it, just rename the <code>__iter__</code> method to e.g. <code>walker</code>, and change the <code>run</code> loop into: <code>for node in rootnode.walker():</code><br> Obviously, the <code>run</code> function could be a method of <code>class Node</code> instead.</p> <p>As you see, I suggest you use directly <code>run(tree, func)</code> instead of binding them to the name <code>printTree</code>, but you can use them in a decorator, or you can make use of the <code>functools.partial</code> function:</p> <pre><code>printTree= functools.partial(run, func=pp) </code></pre> <p>and from then on, you would just</p> <pre><code>printTree(tree) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload