【鼎革‧革鼎】︰ Raspbian Stretch 《六之 J.2 》

派生碼訊

卯 兔

大壯:利貞。

彖曰:大壯,大者壯也。 剛以動,故壯。 大壯利貞﹔大者正也。正大而天地之情可見矣 !

象曰:雷在天上,大壯﹔君子以非禮勿履。

雷 雷鳴在天,聲聞百里。何故『喪羊于易』?《 易 》易曰︰

上六:羝羊觸藩,不能退,不能遂,無攸利 ,艱則吉。

象曰:不能退,不能遂,不祥也。 艱則吉,咎不長也。

派︰同學們,派生《十日談》之《 文 》文摘講︰

如何『』 Python ?就從『』本『派生』的『』開始。因『』故及於它『』它『』,以至於『』而已!!

□︰ 難道都不用練習的嗎?

○︰此語未免太癡!《論語》

學而』篇開宗明義講︰『』而時『』之的吧!!

……

生 ︰《 範 》範說︰程式設計始於『典範』之學習。

python-patterns

A collection of design patterns and idioms in Python.

When an implementation is added or modified, be sure to update this file and rerun append_output.sh (eg. ./append_output.sh borg.py) to keep the output comments at the bottom up to date.

Current Patterns:

Pattern Description
3-tier data<->business logic<->presentation separation (strict relationships)
abstract_factory use a generic function with specific factories
adapter adapt one interface to another using a whitelist
borg a singleton with shared-state among instances
bridge a client-provider middleman to soften interface changes
builder call many little discrete methods rather than having a huge number of constructor parameters
catalog general methods will call different specialized methods based on construction parameter
chain apply a chain of successive handlers to try and process the data
chaining_method continue callback next object method
command bundle a command and arguments to call later
composite encapsulate and provide access to a number of different objects
decorator wrap functionality with other functionality in order to affect outputs
facade use one class as an API to a number of others
factory_method delegate a specialized function/method to create instances
flyweight transparently reuse existing instances of objects with similar/identical state
graph_search (graphing algorithms, not design patterns)
lazy_evaluation lazily-evaluated property pattern in Python
mediator an object that knows how to connect other objects and act as a proxy
memento generate an opaque token that can be used to go back to a previous state
mvc model<->view<->controller (non-strict relationships)
observer provide a callback for notification of events/changes to data
pool preinstantiate and maintain a group of instances of the same type
prototype use a factory and clones of a prototype for new instances (if instantiation is expensive)
proxy an object funnels operations to something else
publish_subscribe a source syndicates events/data to 0+ registered listeners
state logic is org’d into a discrete number of potential states and the next state that can be transitioned to
strategy selectable operations over the same data
template an object imposes a structure but takes pluggable components
visitor invoke a callback for all items of a collection

………

碼 ︰仿 習 。程式初學者,需要多作『模仿』練習,久之 ,熟能生巧。所謂程式『善法』,就是善用其法,因事制宜而已!如果能夠了解什麼是萬物的『性情』︰

『性』 性 一般指得之於天,所以造字時用『生』;『情』 情 得之於環境── 習氣 ──,所以才用『青』,表示後天習得也。故而《三字經》講『性相近,習相遠』。

自然能夠體會程式語言裡講的『物件』之『屬性』和『方法』︰

在程式『思考』中,『性』近『屬性』,物類『固有者』,『情』對應『方法』,或得自於『繼承』,或因『境』而『遷』。

其實是效法『自然之理』,師從『物以類聚』與『遺傳變異』種種之則。不同的『學派』,追求的『重點處』或許『相異』,然而『物件導向』之基本精神還是『一貫相通』的。

─── 《M♪o 之學習筆記本《卯》基件︰【䷡】羝羊觸藩

 

作者本欲詳細解釋

JACK Audio Connection Kit (JACK) Client for Python

之一簡單範例 thru_client.py

pi@raspberrypi:~/jackclient-python/examples $ more thru_client.py 
#!/usr/bin/env python3

"""Create a JACK client that copies input audio directly to the outputs.

This is somewhat modeled after the "thru_client.c" example of JACK 2:
http://github.com/jackaudio/jack2/blob/master/example-clients/thru_client.c

If you have a microphone and loudspeakers connected, this might cause an
acoustical feedback!

"""
import sys
import signal
import os
import jack
import threading

if sys.version_info < (3, 0):
    # In Python 2.x, event.wait() cannot be interrupted with Ctrl+C.
    # Therefore, we disable the whole KeyboardInterrupt mechanism.
    # This will not close the JACK client properly, but at least we can
    # use Ctrl+C.
    signal.signal(signal.SIGINT, signal.SIG_DFL)
else:
    # If you use Python 3.x, everything is fine.
    pass

argv = iter(sys.argv)
# By default, use script name without extension as client name:
defaultclientname = os.path.splitext(os.path.basename(next(argv)))[0]
clientname = next(argv, defaultclientname)
servername = next(argv, None)

client = jack.Client(clientname, servername=servername)

if client.status.server_started:
    print('JACK server started')
if client.status.name_not_unique:
    print('unique name {0!r} assigned'.format(client.name))

event = threading.Event()


@client.set_process_callback
def process(frames):
    assert len(client.inports) == len(client.outports)
    assert frames == client.blocksize
    for i, o in zip(client.inports, client.outports):
        o.get_buffer()[:] = i.get_buffer()


@client.set_shutdown_callback
def shutdown(status, reason):
    print('JACK shutdown!')
    print('status:', status)
    print('reason:', reason)
    event.set()


# create two port pairs
for number in 1, 2:
    client.inports.register('input_{0}'.format(number))
    client.outports.register('output_{0}'.format(number))

with client:
    # When entering this with-statement, client.activate() is called.
    # This tells the JACK server that we are ready to roll.
    # Our process() callback will start running now.

    # Connect the ports.  You can't do this before the client is activated,
    # because we can't make connections to clients that aren't running.
    # Note the confusing (but necessary) orientation of the driver backend
    # ports: playback ports are "input" to the backend, and capture ports
    # are "output" from it.

    capture = client.get_ports(is_physical=True, is_output=True)
    if not capture:
        raise RuntimeError('No physical capture ports')

    for src, dest in zip(capture, client.inports):
        client.connect(src, dest)

    playback = client.get_ports(is_physical=True, is_input=True)
    if not playback:
        raise RuntimeError('No physical playback ports')

    for src, dest in zip(client.outports, playback):
        client.connect(src, dest)

    print('Press Ctrl+C to stop')
    try:
        event.wait()
    except KeyboardInterrupt:
        print('\nInterrupted by user')

# When the above with-statement is left (either because the end of the
# code block is reached, or because an exception was raised inside),
# client.deactivate() and client.close() are called automatically.

 

以為開端,或可當作寫法樣板。怎知卻遇着 @ 『裝飾子』也!不得已當文抄公乎?

PEP 318 — Decorators for Functions and Methods

Abstract

The current method for transforming functions and methods (for instance, declaring them as a class or static method) is awkward and can lead to code that is difficult to understand. Ideally, these transformations should be made at the same point in the code where the declaration itself is made. This PEP introduces new syntax for transformations of a function or method declaration.

Motivation

The current method of applying a transformation to a function or method places the actual transformation after the function body. For large functions this separates a key component of the function’s behavior from the definition of the rest of the function’s external interface. For example:

def foo(self):
    perform method operation
foo = classmethod(foo)

This becomes less readable with longer methods. It also seems less than pythonic to name the function three times for what is conceptually a single declaration. A solution to this problem is to move the transformation of the method closer to the method’s own declaration. The intent of the new syntax is to replace

def foo(cls):
    pass
foo = synchronized(lock)(foo)
foo = classmethod(foo)

with an alternative that places the decoration in the function’s declaration:

@classmethod
@synchronized(lock)
def foo(cls):
    pass

Modifying classes in this fashion is also possible, though the benefits are not as immediately apparent. Almost certainly, anything which could be done with class decorators could be done using metaclasses, but using metaclasses is sufficiently obscure that there is some attraction to having an easier way to make simple modifications to classes. For Python 2.4, only function/method decorators are being added.

PEP 3129 [#PEP-3129] proposes to add class decorators as of Python 2.6.

Why Is This So Hard?

Two decorators (classmethod() and staticmethod()) have been available in Python since version 2.2. It’s been assumed since approximately that time that some syntactic support for them would eventually be added to the language. Given this assumption, one might wonder why it’s been so difficult to arrive at a consensus. Discussions have raged off-and-on at times in both comp.lang.python and the python-dev mailing list about how best to implement function decorators. There is no one clear reason why this should be so, but a few problems seem to be most divisive.

  • Disagreement about where the “declaration of intent” belongs. Almost everyone agrees that decorating/transforming a function at the end of its definition is suboptimal. Beyond that there seems to be no clear consensus where to place this information.
  • Syntactic constraints. Python is a syntactically simple language with fairly strong constraints on what can and can’t be done without “messing things up” (both visually and with regards to the language parser). There’s no obvious way to structure this information so that people new to the concept will think, “Oh yeah, I know what you’re doing.” The best that seems possible is to keep new users from creating a wildly incorrect mental model of what the syntax means.
  • Overall unfamiliarity with the concept. For people who have a passing acquaintance with algebra (or even basic arithmetic) or have used at least one other programming language, much of Python is intuitive. Very few people will have had any experience with the decorator concept before encountering it in Python. There’s just no strong preexisting meme that captures the concept.
  • Syntax discussions in general appear to cause more contention than almost anything else. Readers are pointed to the ternary operator discussions that were associated with PEP 308 for another example of this.

On the name ‘Decorator’

There’s been a number of complaints about the choice of the name ‘decorator’ for this feature. The major one is that the name is not consistent with its use in the GoF book[11]. The name ‘decorator’ probably owes more to its use in the compiler area — a syntax tree is walked and annotated. It’s quite possible that a better name may turn up.

Current Syntax

The current syntax for function decorators as implemented in Python 2.4a2 is:

@dec2
@dec1
def func(arg1, arg2, ...):
    pass

This is equivalent to:

def func(arg1, arg2, ...):
    pass
func = dec2(dec1(func))

without the intermediate assignment to the variable func. The decorators are near the function declaration. The @ sign makes it clear that something new is going on here.

The rationale for the order of application [16] (bottom to top) is that it matches the usual order for function-application. In mathematics, composition of functions (g o f)(x) translates to g(f(x)). In Python, @g @f def foo() translates to foo=g(f(foo).

The decorator statement is limited in what it can accept — arbitrary expressions will not work. Guido preferred this because of a gut feeling [17].

The current syntax also allows decorator declarations to call a function that returns a decorator:

@decomaker(argA, argB, ...)
def func(arg1, arg2, ...):
    pass

This is equivalent to:

func = decomaker(argA, argB, ...)(func)

The rationale for having a function that returns a decorator is that the part after the @ sign can be considered to be an expression (though syntactically restricted to just a function), and whatever that expression returns is called. See declaration arguments [16].

Why @?

There is some history in Java using @ initially as a marker in Javadoc comments [24] and later in Java 1.5 for annotations [10], which are similar to Python decorators. The fact that @ was previously unused as a token in Python also means it’s clear there is no possibility of such code being parsed by an earlier version of Python, leading to possibly subtle semantic bugs. It also means that ambiguity of what is a decorator and what isn’t is removed. That said, @ is still a fairly arbitrary choice. Some have suggested using | instead.

For syntax options which use a list-like syntax (no matter where it appears) to specify the decorators a few alternatives were proposed: [|...|], *[...]*, and <...>.

───

PEP 3129 — Class Decorators

Abstract

This PEP proposes class decorators, an extension to the function and method decorators introduced in PEP 318.

Rationale

When function decorators were originally debated for inclusion in Python 2.4, class decorators were seen as obscure and unnecessary [1] thanks to metaclasses. After several years’ experience with the Python 2.4.x series of releases and an increasing familiarity with function decorators and their uses, the BDFL and the community re-evaluated class decorators and recommended their inclusion in Python 3.0 [2].

The motivating use-case was to make certain constructs more easily expressed and less reliant on implementation details of the CPython interpreter. While it is possible to express class decorator-like functionality using metaclasses, the results are generally unpleasant and the implementation highly fragile [3]. In addition, metaclasses are inherited, whereas class decorators are not, making metaclasses unsuitable for some, single class-specific uses of class decorators. The fact that large-scale Python projects like Zope were going through these wild contortions to achieve something like class decorators won over the BDFL.

Semantics

The semantics and design goals of class decorators are the same as for function decorators ([4], [5]); the only difference is that you’re decorating a class instead of a function. The following two snippets are semantically identical:

class A:
  pass
A = foo(bar(A))


@foo
@bar
class A:
  pass

For a detailed examination of decorators, please refer to PEP 318.

 

還得請讀者先行自修的哩◎

Python Course

Decorators

Introduction

Decorators belong most probably to the most beautiful and most powerful design possibilities in Python, but at the same time the concept is considered by many as complicated to get into. To be precise, the usage of decorates is very easy, but writing decorators can be complicated, especially if you are not experienced with decorators and some functional programming concepts.

Even though it is the same underlying concept, we have two different kinds of decorators in Python:

  • Function decorators
  • Class decorators

A decorator in Python is any callable Python object that is used to modify a function or a class. A reference to a function “func” or a class “C” is passed to a decorator and the decorator returns a modified function or class. The modified functions or classes usually contain calls to the original function “func” or class “C”.

You may also consult our chapter on memoization with decorators.

If you like the image on the right side of this page and if you are also interested in image processing with Python, Numpy, Scipy and Matplotlib, you will definitely like our chapter on Image Processing Techniques, it explains the whole process of the making-of of our decorator and at sign picture!