(original) (raw)
On 8 December 2017 at 19:28, Raymond Hettinger <raymond.hettinger@gmail.com> wrote:
I'm hoping the typing experts will chime in here. The question is straight-forward. Where should we look for the signature and docstring for constructing instances? Should they be attached to the class, to \_\_init\_\_(), or to \_\_new\_\_() when it used.
It would be nice to have an official position on that before, it gets set in stone through arbitrary choices made by pycharm, pydoc, mypy, typing.NamedTuple, and dataclasses.dataclass.
Here are some thoughts about this:
1\. Instance variables are given very little attention in pydoc. Consider this example:
>>> class C:
... x: int = 1
... def meth(self, y: int) -> None:
... ...
>>> help(C)
... x: int = 1
... def meth(self, y: int) -> None:
... ...
>>> help(C)
Help on class C in module \_\_main\_\_:
class C(builtins.object)
| Methods defined here:
|
| meth(self, y: int) -> None
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| \_\_dict\_\_
| dictionary for instance variables (if defined)
|
| \_\_weakref\_\_
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| \_\_annotations\_\_ = {'x': }
|
| x = 1
class C(builtins.object)
| Methods defined here:
|
| meth(self, y: int) -> None
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| \_\_dict\_\_
| dictionary for instance variables (if defined)
|
| \_\_weakref\_\_
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| \_\_annotations\_\_ = {'x': }
|
| x = 1
The methods defined are listed first and are nicely formatted, while variables together with \_\_annotations\_\_ are
left at the very end. I think that a line like
x: int = 1
should appear for every instance variable should appear first, even before methods, since this is how people write (and read) classes.
See also https://bugs.python.org/issue28519 for another problem with pydoc.
2\. pydoc already extracts the signature of class from \_\_init\_\_ and \_\_new\_\_ (giving the preference to later if both are present) including
the type annotations. I think this can be kept as is, but the special constructs like NamedTuple and dataclass that auto-generate methods should
add annotations to them. For example, there is an issue to add annotations to \_\_new\_\_ by NamedTuple, see https://bugs.python.org/issue31006
--
Ivan