Rock It 《ML》JupyterLab 【丁】Code《七》語義【五】鴨子?!

假使從『裝置的程式介面』 API 來觀察『裝置』是什麼?『裝置』不過就是透過那個『 API 規範』存取的 □□○○!這可引發了一個『大哉問』?如果說某種『物理裝置』事實上沒有連上系統,但是它的『API 介面』卻『存在』且能『運作』,那麼我們『能不能』知道那個『裝置』實際上不存在的呢??這個問題其實比表面深沈 的多,一直延伸到『知識論』的哲學爭議之上。比方說,什麼是『蘋果樹 』?如何判定『某個水果』是『蘋果』?最終總容易落入用『外在屬性』來作『歸類』的事實裡。更不要講過去的『接枝』到現今的『基改』,所作的『跨界』之事!也許當『界線』越來越模糊,『什麼是什麼』的問題終將越來越不清楚的耶!!

這『何謂鴨子』之事也發生在『物件導向』的語言中。維基百科的『鴨子型別』講︰

當看到一隻鳥走起來像鴨子、游泳起來像鴨子、叫起來也像鴨子,那麼這隻鳥就可以被稱為鴨子。

Duck typing

In computer programming with object-oriented programming languages, duck typing is a layer of programming language and design rules on top of typing. Typing is concerned with assigning a type to any object. Duck typing is concerned with establishing the suitability of an object for some purpose. With normal typing, suitability is assumed to be determined by an object’s type only. In duck typing, an object’s suitability is determined by the presence of certain methods and properties (with appropriate meaning), rather than the actual type of the object.

The name of the concept refers to the duck test, attributed to James Whitcomb Riley, which may be phrased as follows:

When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.[1]

In duck typing, a programmer is only concerned with ensuring that objects behave as demanded of them in a given context, rather than ensuring that they are of a specific type. For example, in a non-duck-typed language, one would create a function that requires that the object passed into it be of type Duck, in order to ensure that that function can then use the object’s walk and quack methods. In a duck-typed language, the function would take an object of any type and simply call its walk and quack methods, producing a run-time error if they are not defined. Instead of specifying types formally, duck typing practices rely on documentation, clear code, and testing to ensure correct use.

───

Criticism

One issue with duck typing is that it forces programmers to have a much wider understanding of the code they are working with at any given time. For instance, in Python, one could easily create a class called Wine, which expects a class implementing the “press” attribute as an ingredient. However, a class called Trousers might also implement the press() method. With duck typing, in order to prevent strange, hard-to-detect errors, the developer needs to be aware of each potential use of the method “press”, even when it’s conceptually unrelated to what they are working on. By way of contrast, in a strongly and statically typed language that uses type hierarchies and parameter type checking, it’s much harder to supply an unexpected object type to a class. For example, in a language like Java, the ambiguity in the above reuse of the method name press() would not be a problem unless one of the two classes was deliberately defined as a child of the other.

Proponents of duck typing, such as Guido van Rossum, argue that the issue is handled by testing, and the necessary knowledge of the codebase required to maintain it.[4][5]

Criticisms around duck typing tend to be special cases of broader points of contention regarding dynamically typed versus statically typed programming language semantics.

勇闖新世界︰ 《 KERNEL 4.X 》之整裝蓄勢‧設備管理及應用‧三上

 

莫非『吉多』 Guido 對『鴨子』的看法改變了?

PEP 484 — Type Hints

Abstract

PEP 3107 introduced syntax for function annotations, but the semantics were deliberately left undefined. There has now been enough 3rd party usage for static type analysis that the community would benefit from a standard vocabulary and baseline tools within the standard library.

This PEP introduces a provisional module to provide these standard definitions and tools, along with some conventions for situations where annotations are not available.

Note that this PEP still explicitly does NOT prevent other uses of annotations, nor does it require (or forbid) any particular processing of annotations, even when they conform to this specification. It simply enables better coordination, as PEP 333 did for web frameworks.

For example, here is a simple function whose argument and return type are declared in the annotations:

def greeting(name: str) -> str:
    return 'Hello ' + name

While these annotations are available at runtime through the usual __annotations__ attribute, no type checking happens at runtime. Instead, the proposal assumes the existence of a separate off-line type checker which users can run over their source code voluntarily. Essentially, such a type checker acts as a very powerful linter. (While it would of course be possible for individual users to employ a similar checker at run time for Design By Contract enforcement or JIT optimization, those tools are not yet as mature.)

The proposal is strongly inspired by mypy [mypy]. For example, the type “sequence of integers” can be written as Sequence[int]. The square brackets mean that no new syntax needs to be added to the language. The example here uses a custom type Sequence, imported from a pure-Python module typing. The Sequence[int] notation works at runtime by implementing __getitem__() in the metaclass (but its significance is primarily to an offline type checker).

The type system supports unions, generic types, and a special type named Any which is consistent with (i.e. assignable to and from) all types. This latter feature is taken from the idea of gradual typing. Gradual typing and the full type system are explained in PEP 483.

Other approaches from which we have borrowed or to which ours can be compared and contrasted are described in PEP 482.

Rationale and Goals

PEP 3107 added support for arbitrary annotations on parts of a function definition. Although no meaning was assigned to annotations then, there has always been an implicit goal to use them for type hinting [gvr-artima], which is listed as the first possible use case in said PEP.

This PEP aims to provide a standard syntax for type annotations, opening up Python code to easier static analysis and refactoring, potential runtime type checking, and (perhaps, in some contexts) code generation utilizing type information.

Of these goals, static analysis is the most important. This includes support for off-line type checkers such as mypy, as well as providing a standard notation that can be used by IDEs for code completion and refactoring.

 

其實沒有哩!

Non-goals

While the proposed typing module will contain some building blocks for runtime type checking — in particular the get_type_hints() function — third party packages would have to be developed to implement specific runtime type checking functionality, for example using decorators or metaclasses. Using type hints for performance optimizations is left as an exercise for the reader.

It should also be emphasized that Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.

 

當下 Python 版本 3.5.3︰

rock64@rock64:~$ ipython3
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: def greeting(name: str) -> str: 
   ...:     return 'Hello ' + name 
   ...:                                                                         

In [2]: greeting("foo")                                                         
Out[2]: 'Hello foo'

In [3]: greeting(123)                                                           
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-fe206e138e19> in <module>
----> 1 greeting(123)

<ipython-input-1-93ff6dea8645> in greeting(name)
      1 def greeting(name: str) -> str:
----> 2     return 'Hello ' + name
      3 

TypeError: Can't convert 'int' object to str implicitly

 

符合

/mypy

Optional static typing for Python 2 and 3 (PEP 484) http://www.mypy-lang.org/

mypy logo

Mypy: Optional Static Typing for Python

Build Status Chat at https://gitter.im/python/typing Checked with mypy

Got a question? Join us on Gitter!

We don’t have a mailing list; but we are always happy to answer questions on gitter chat. If you are sure you’ve found a bug please search our issue trackers for a duplicate before filing a new issue:

What is mypy?

Mypy is an optional static type checker for Python. You can add type hints (PEP 484) to your Python programs, and use mypy to type check them statically. Find bugs in your programs without even running them!

You can mix dynamic and static typing in your programs. You can always fall back to dynamic typing when static typing is not convenient, such as for legacy code.

Here is a small example to whet your appetite (Python 3):

from typing import Iterator

def fib(n: int) -> Iterator[int]:
    a, b = 0, 1
    while a < n:
        yield a
        a, b = b, a + b

See the documentation for more examples.

 

Requirements

You need Python 3.4 or later to run mypy. You can have multiple Python versions (2.x and 3.x) installed on the same system without problems.

In Ubuntu, Mint and Debian you can install Python 3 like this:

sudo pip3 install mypy

 

何不思考『動‧靜』 Typing 各自好處也☆