LangageDocumentation

[wiki: Documentation]

PageOutline

Comment insérer ou récupérer de la documentation sur votre code et sur les éléments intégrés du langage ?

Commentaires

Sur chaque ligne, l’interpréteur ignore le caractère ‘#’ et tout ce qui le suit, à condition qu’il ne soit pas inclus dans une chaîne de caractères littérale.

>>> # commentaire


>>> print(1) # un autre commentaire
1

>>> texte = '1 # non commentaire'
>>> print(texte)
1 # non commentaire


Fonction dir()

  • La fonction intégrée dir() permet de lister les attributs de tout objet, variables et fonctions.
  • Cela s’applique aux modules.
  • Cela s’applique aux variables littérales des types prédéfinis, y compris les collections.
  • On peut donner le nom d’un type
>>> import sys


>>> dir(sys)
['displayhook', 'doc', 'excepthook', 'name', 'package',
'stderr', 'stdin', 'stdout', '_clear_type_cache', '_current_frames',
'_getframe', '_mercurial', 'api_version',
'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats',
'copyright', 'displayhook', 'dllhandle', 'dont_write_bytecode', 'exc_clear',
'exc_info', 'exc_traceback', 'exc_type', 'exc_value', 'excepthook', 'exec_prefix',
'executable', 'exit', 'flags', 'float_info', 'float_repr_style', 'getcheckinterval',
'getdefaultencoding', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit',
'getrefcount', 'getsizeof', 'gettrace', 'getwindowsversion', 'hexversion',
'long_info', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules',
'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix',
'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecursionlimit',
'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version',
'version_info', 'warnoptions', 'winver']

>>> dir(3)
['abs', 'add', 'and', 'class', 'cmp', 'coerce',
'delattr', 'div', 'divmod', 'doc', 'float', 'floordiv',
'format', 'getattribute', 'getnewargs', 'hash', 'hex',
'index', 'init', 'int', 'invert', 'long', 'lshift',
'mod', 'mul', 'neg', 'new', 'nonzero', 'oct', 'or',
'pos', 'pow', 'radd', 'rand', 'rdiv', 'rdivmod',
'reduce', 'reduce_ex', 'repr', 'rfloordiv', 'rlshift',
'rmod', 'rmul', 'ror', 'rpow', 'rrshift', 'rshift',
'rsub', 'rtruediv', 'rxor', 'setattr', 'sizeof', 'str',
'sub', 'subclasshook', 'truediv', 'trunc', 'xor', 'bit_length',
'conjugate', 'denominator', 'imag', 'numerator', 'real']

>>> dir([])
['add', 'class', 'contains', 'delattr', 'delitem', 'delslice',
'doc', 'eq', 'format', 'ge', 'getattribute', 'getitem',
'getslice', 'gt', 'hash', 'iadd', 'imul', 'init', 'iter',
'le', 'len', 'lt', 'mul', 'ne', 'new', 'reduce',
'reduce_ex', 'repr', 'reversed', 'rmul', 'setattr', 'setitem',
'setslice', 'sizeof', 'str', 'subclasshook', 'append', 'count',
'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

>>> dir([]) == dir(list)
True

>>>dir(str)
['add', 'class', 'contains', 'delattr', 'doc', 'eq',
'format', 'ge', 'getattribute', 'getitem', 'getnewargs',
'getslice', 'gt', 'hash', 'init', 'le', 'len', 'lt',
'mod', 'mul', 'ne', 'new', 'reduce', 'reduce_ex',
'repr', 'rmod', 'rmul', 'setattr', 'sizeof', 'str',
'subclasshook', '_formatter_field_name_split', '_formatter_parser',
'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs',
'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']


Chaines de documentation (docstrings)

  • Au delà des commentaires, on peut doter un objet d’une documentation courte, consultable à l’exécution.
  • Syntaxiquement, on insère une chaîne de caractère en haut d’un module, d’une fonction ou d’une classe, avant toute instruction exécutable.
  • Une telle chaîne est automatiquement stockée dans l’attribut doc de l’objet.
  • Cette chaîne peut être multi-lignes, comme dans ce fichier vecteurs3d.py :
#!python
"""
Le module vecteurs3d permet de manipuler des
tuples de trois éléments.
"""


def norme(v):
'Calcul de la norme d'un tuple de trois coordonnées.'
x2 = v[0]**2
y2 = v[1]**2
z2 = v[2]**2
return (x2+y2+z2)**(1/2)

def produit(v1,v2):
'Multiplication terme à terme de deux tuples.'
x = v1[0]*v2[0]
y = v1[1]*v2[1]
z = v1[2]*v2[2]
return x,y,z


  • Il n’y a pas de convention répandue sur la façon d’écrire vos chaines de documentation.
  • Les modules et fonction intégrées sont dotées de chaines de documentation :
#!python


>>> import sys
>>> print sys.doc
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.

Dynamic objects:

argv -- command line arguments; argv[0] is the script pathname if known
path -- module search path; path[0] is the script directory, else ''
modules -- dictionary of loaded modules

displayhook -- called to show results in an interactive session
excepthook -- called to handle any uncaught exception other than SystemExit
To customize printing in an interactive session or to install a custom
top-level exception handler, assign other functions to replace these.

exitfunc -- if sys.exitfunc exists, this routine is called when Python exits
Assigning to sys.exitfunc is deprecated; use the atexit module instead.

stdin -- standard input file object; used by raw_input() and input()
stdout -- standard output file object; used by the print statement
stderr -- standard error object; used for error messages
By assigning other file objects (or objects that behave like files)
to these, it is possible to redirect all of the interpreter's I/O.

last_type -- type of last uncaught exception
last_value -- value of last uncaught exception
last_traceback -- traceback of last uncaught exception
These three are only available in an interactive session after a
traceback has been printed.

exc_type -- type of exception currently being handled
exc_value -- value of exception currently being handled
exc_traceback -- traceback of exception currently being handled
The function exc_info() should be used instead of these three,
because it is thread-safe.

Static objects:

float_info -- a dict with information about the float inplementation.
long_info -- a struct sequence with information about the long implementation.
maxint -- the largest supported integer (the smallest is -maxint-1)
maxsize -- the largest supported length of containers.
maxunicode -- the largest supported character
builtin_module_names -- tuple of module names built into this interpreter
version -- the version of this interpreter as a string
version_info -- version information as a named tuple
hexversion -- version information encoded as a single integer
copyright -- copyright notice pertaining to this interpreter
platform -- platform identifier
executable -- absolute path of the executable binary of the Python interpreter
prefix -- prefix used to find the Python library
exec_prefix -- prefix used to find the machine-specific Python library
float_repr_style -- string indicating the style of repr() output for floats
dllhandle -- [Windows only] integer handle of the Python DLL
winver -- [Windows only] version number of the Python DLL
stdin -- the original stdin; don't touch!
stdout -- the original stdout; don't touch!
stderr -- the original stderr; don't touch!
displayhook -- the original displayhook; don't touch!
excepthook -- the original excepthook; don't touch!

Functions:

displayhook() -- print an object to the screen, and save it in builtin._
excepthook() -- print an exception and its traceback to sys.stderr
exc_info() -- return thread-safe information about the current exception
exc_clear() -- clear the exception state for the current thread
exit() -- exit the interpreter by raising SystemExit
getdlopenflags() -- returns flags to be used for dlopen() calls
getprofile() -- get the global profiling function
getrefcount() -- return the reference count for an object (plus one :-)
getrecursionlimit() -- return the max recursion depth for the interpreter
getsizeof() -- return the size of an object in bytes
gettrace() -- get the global debug tracing function
setcheckinterval() -- control how often the interpreter checks for events
setdlopenflags() -- set the flags to be used for dlopen() calls
setprofile() -- set the global profiling function
setrecursionlimit() -- set the max recursion depth for the interpreter
settrace() -- set the global debug tracing function

>>> print sys.getrefcount.doc
getrefcount(object) -> integer

Return the reference count of object. The count returned is generally
one higher than you might expect, because it includes the (temporary)
reference as an argument to getrefcount().


  • Ansi que les fonctions intégrées :
#!python


>>> print int.doc
int(x=0) -> int or long
int(x, base=10) -> int or long

Convert a number or string to an integer, or return 0 if no arguments
are given. If x is floating point, the conversion truncates towards zero.
If x is outside the integer range, the function returns a long instead.

If x is not a number or if base is given, then x must be a string or
Unicode object representing an integer literal in the given base. The
literal can be preceded by '+' or '-' and be surrounded by whitespace.
The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to
interpret the base from the string as an integer literal.
>>> int('0b100', base=0)
4


!PyDoc : fonction help()

La fonction help() est capable d’inspecter toutes les informations internes d’un module, d’une fonction ou d’une classe, y compris les chaine de documentation, afin de construire une documentation consultable en ligne avec une mise en page améliorée. Par exemple, en reprenant le fichier vecteurs3d.py décrit plus haut :

#!python


>>> import vecteurs3d
>>> help(vecteurs3d)
NAME
vecteurs3d

DESCRIPTION
Le module vecteurs3d permet de manipuler des
tuples de trois éléments.

FUNCTIONS
norme(v)
Calcul de la norme d'un tuple de trois coordonnées.

produit(v1, v2)
Multiplication terme à terme de deux tuples.


Cela fonctionne avec tous les éléments intégrés du langage et de la bibliothèque standard :

#!python


>>> help(str.replace)
Help on method_descriptor:

replace(...)
S.replace(old, new[, count]) -> string

Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.


!PyDoc : rapport HTML

!PyDoc est également capable de générer des pages HTML. Cela a peu d’intérêt pour les eléments prédéfinis, qui sont mieux décrits dans le site web officiel. Par contre, c’est un moyen simple de générer des pages HTML à partir de vos propres fichiers. Cette opération ne s’effectue pas au sein de l’interpréteur, mais à partir d’un programme spécial :

1. Ajoutez vos répertoires de développement à la variable PYTHONPATH
1. Lancez !PyDoc (en windows : pythonw c:\Python27\Tools\scripts\pydocgui.pyw).
1. Nommez le module qui vous intéresse et lancez la recherche.
1. Sélectionner le module… cela ouvrira une fenêtre dans votre navigateur.

Sphinx

Site web officiel

Pour les eléments standards, rien n’égale la documentation web officielle, qui comprend entre autres :

Le tout en variante 2 comme en variante 3.