• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

_pytest/H03-May-2022-10176

django/H03-May-2022-12688

lettuce/H03-May-2022-8164

nose/H03-May-2022-188136

numpy/H03-May-2022-5,7894,364

py/H03-May-2022-642459

pytest/H03-May-2022-349249

README.mdH A D06-Oct-20208.9 KiB245181

StringIO.pyH A D06-Oct-20202.7 KiB12792

alembic.pyH A D06-Oct-2020144 74

behave.pyH A D06-Oct-20201.8 KiB6051

cStringIO.pyH A D06-Oct-20202.7 KiB13295

copy.pyH A D06-Oct-2020235 1913

struct.pyH A D06-Oct-20202.3 KiB10776

README.md

1Python Skeletons
2================
3
4_This proposal is a draft._
5
6Python skeletons are Python files that contain API definitions of existing
7libraries extended for static analysis tools.
8
9Rationale
10---------
11
12Python is a dynamic language less suitable for static code analysis than static
13languages like C or Java. Although Python static analysis tools can extract
14some information from Python source code without executing it, this information
15is often very shallow and incomplete.
16
17Dynamic features of Python are very useful for user code. But using these
18features in APIs of third-party libraries and the standard library is not
19always a good idea. Tools (and users, in fact) need clear definitions of APIs.
20Often library API definitions are quite static and easy to grasp (defined
21using `class`, `def`), but types of function parameters and return values
22usually are not specified. Sometimes API definitions involve metaprogramming.
23
24As there is not enough information in API definition code of libraries,
25developers of static analysis tools collect extended API data themselves and
26store it in their own formats. For example, PyLint uses imperative AST
27transformations of API modules in order to extend them with hard-coded data.
28PyCharm extends APIs via its proprietary database of declarative type
29annotations. The absence of a common extended API information format makes it
30hard for developers and users of tools to collect and share data.
31
32
33Proposal
34--------
35
36The proposal is to create a common database of extended API definitions as a
37collection of Python files called skeletons. Static analysis tools already
38understand Python code, so it should be easy to start extracting API
39definitions from these Python skeleton files. Regular function and class
40definitions can be extended with additional docstrings and decorators, e.g. for
41providing types of function parameters and return values. Static analysis tools
42may use a subset of information contained in skeleton files needed for their
43operation. Using Python files instead of a custom API definition format will
44also make it easier for users to populate the skeletons database.
45
46Declarative Python API definitions for static analysis tools cannot cover all
47dynamic tricks used in real APIs of libraries: some of them still require
48library-specific code analysis. Nevertheless the skeletons database is enough
49for many libraries.
50
51The proposed [python-skeletons](https://github.com/JetBrains/python-skeletons)
52repository is hosted on GitHub.
53
54
55Conventions
56-----------
57
58Skeletons should contain syntactically correct Python code, preferably compatible
59with Python 2.6-3.3.
60
61Skeletons should respect [PEP-8](http://www.python.org/dev/peps/pep-0008/) and
62[PEP-257](http://www.python.org/dev/peps/pep-0257/) style guides.
63
64If you need to reference the members of the original module of a skeleton, you
65should import it explicitly. For example, in a skeleton for the `foo` module:
66
67```python
68import foo
69
70
71class C(foo.B):
72    def bar():
73        """Do bar and return Bar.
74
75        :rtype: foo.Bar
76        """
77        return foo.Bar()
78```
79Modules can be referenced in docstring without explicit imports.
80
81The body of a function in a skeleton file should consist of a single `return`
82statement that returns a simple value of the declared return type (e.g. `0`
83for `int`, `False` for `bool`, `Foo()` for `Foo`). If the function returns
84something non-trivial, its may consist of a `pass` statement.
85
86
87### Types
88
89There is no standard notation for specifying types in Python code. We would
90like this standard to emerge, see the related work below.
91
92The current understanding is that a standard for optional type annotations in
93Python could use the syntax of function annotations in Python 3 and decorators
94as a fallback in Python 2. The type system should be relatively simple, but it
95has to include parametric (generic) types for collections and probably more.
96
97As a temporary solution, we propose a simple way of specifying types in
98skeletons using Sphinx docstrings using the following notation:
99
100    Foo                # Class Foo visible in the current scope
101    x.y.Bar            # Class Bar from x.y module
102    Foo | Bar          # Foo or Bar
103    (Foo, Bar)         # Tuple of Foo and Bar
104    list[Foo]          # List of Foo elements
105    dict[Foo, Bar]     # Dict from Foo to Bar
106    T                  # Generic type (T-Z are reserved for generics)
107    T <= Foo           # Generic type with upper bound Foo
108    Foo[T]             # Foo parameterized with T
109    (Foo, Bar) -> Baz  # Function of Foo and Bar that returns Baz
110
111There are several shortcuts available:
112
113    unknown            # Unknown type
114    None               # type(None)
115    string             # Py2: str | unicode, Py3: str
116    bytestring         # Py2: str | unicode, Py3: bytes
117    bytes              # Py2: str, Py3: bytes
118    unicode            # Py2: unicode, Py3: str
119
120The syntax is a subject to change. It is almost compatible to Python (except
121function types), but its semantics differs from Python (no `|`, no implicitly
122visible names, no generic types). So you cannot use these expressions in
123Python 3 function annotations.
124
125If you want to create a parameterized class, you should define its parameters
126in the mock return type of a constructor:
127
128```python
129class C(object):
130    """Some collection C that can contain values of T."""
131
132    def __init__(self, value):
133        """Initialize C.
134
135        :type value: T
136        :rtype: C[T]
137        """
138        pass
139
140    def get(self):
141        """Return the contained value.
142
143        :rtype: T
144        """
145        pass
146```
147
148
149### Versioning
150
151The recommended way of checking the version of Python is:
152
153```python
154import sys
155
156
157if sys.version_info >= (2, 7) and sys.version_info < (3,):
158    def from_27_until_30():
159        pass
160```
161
162A skeleton should document the most recently released version of a library. Use
163deprecation warnings for functions that have been removed from the API.
164
165Skeletons for built-in symbols is an exception. There are two modules:
166`__builtin__` for Python 2 and `builtins` for Python 3.
167
168
169Related Work
170------------
171
172The JavaScript community is also interested in formalizing API definitions and
173specifying types. They have come up with several JavaScript dialects that
174support optional types: TypeScript, Dart. There is a JavaScript initiative
175similar to the proposed Python skeletons called
176[DefinitelyTyped](https://github.com/borisyankov/DefinitelyTyped). The idea is
177to use TypeScript API stubs for various JavaScript libraries.
178
179There are many approaches to specifying types in Python, none of them is widely
180adopted at the moment:
181
182* A series of old (2005) posts by GvR:
183  [1](http://www.artima.com/weblogs/viewpost.jsp?thread=85551),
184  [2](http://www.artima.com/weblogs/viewpost.jsp?thread=86641),
185  [3](http://www.artima.com/weblogs/viewpost.jsp?thread=87182)
186* String-based [python-rightarrow](https://github.com/kennknowles/python-rightarrow)
187  library
188* Expression-based [typeannotations](https://github.com/ceronman/typeannotations)
189  library for Python 3
190* [mypy](http://www.mypy-lang.org/) Python dialect
191* [pytypes](https://github.com/pytypes/pytypes): Optional typing for Python proposal
192* [Proposal: Use mypy syntax for function annotations](https://mail.python.org/pipermail/python-ideas/2014-August/028618.html) by GvR
193
194See also the notes on function annotations in
195[PEP-8](http://www.python.org/dev/peps/pep-0008/).
196
197
198PyCharm / IntelliJ IDEA
199-----------------------
200
201PyCharm 3 and the Python plugin 3.x for IntelliJ IDEA can extract the following
202information from the skeletons:
203
204* Parameters of functions and methods
205* Return types and parameter types of functions and methods
206* Types of assignment targets
207* Extra module members
208* Extra class members
209* TODO
210
211PyCharm 3 comes with a snapshot of the Python skeletons repository (Python
212plugin 3.0.1 for IntelliJ IDEA still doesn't include this repository). You
213**should not** modify it, because it will be updated with the PyCharm / Python
214plugin for IntelliJ IDEA installation. If you want to change the skeletons, clone
215the skeletons GitHub repository into your PyCharm/IntelliJ IDEA config directory:
216
217```bash
218cd <config directory>
219git clone https://github.com/JetBrains/python-skeletons.git
220```
221
222where `<config directory>` is:
223
224* PyCharm
225    * macOS: `~/Library/Application Support/JetBrains/PyCharmXX`
226    * Linux: `~/.config/JetBrains/PyCharmXX`
227    * Windows: `<User home>\AppData\Roaming\JetBrains\PyCharmXX`
228* IntelliJ IDEA
229    * macOS: `~/Library/Application Support/JetBrains/IntelliJIdeaXX`
230    * Linux: `~/.config/JetBrains/IntelliJIdeaXX`
231    * Windows: `<User home>\AppData\Roaming\JetBrains\IntelliJIdeaXX`
232
233Please send your PyCharm/IntelliJ-related bug reports and feature requests to
234[PyCharm issue tracker](https://youtrack.jetbrains.com/issues/PY).
235
236
237Feedback
238--------
239
240If you want to contribute, send your pull requests to the Python skeletons
241repository on GitHub. Please make sure, that you follow the conventions above.
242
243Use [code-quality](http://mail.python.org/mailman/listinfo/code-quality)
244mailing list to discuss Python skeletons.
245