README.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. .. funcsigs documentation master file, created by
  2. sphinx-quickstart on Fri Apr 20 20:27:52 2012.
  3. You can adapt this file completely to your liking, but it should at least
  4. contain the root `toctree` directive.
  5. Introducing funcsigs
  6. ====================
  7. The Funcsigs Package
  8. --------------------
  9. ``funcsigs`` is a backport of the `PEP 362`_ function signature features from
  10. Python 3.3's `inspect`_ module. The backport is compatible with Python 2.6, 2.7
  11. as well as 3.3 and up. 3.2 was supported by version 0.4, but with setuptools and
  12. pip no longer supporting 3.2, we cannot make any statement about 3.2
  13. compatibility.
  14. Compatibility
  15. `````````````
  16. The ``funcsigs`` backport has been tested against:
  17. * CPython 2.6
  18. * CPython 2.7
  19. * CPython 3.3
  20. * CPython 3.4
  21. * CPython 3.5
  22. * CPython nightlies
  23. * PyPy and PyPy3(currently failing CI)
  24. Continuous integration testing is provided by `Travis CI`_.
  25. Under Python 2.x there is a compatibility issue when a function is assigned to
  26. the ``__wrapped__`` property of a class after it has been constructed.
  27. Similiarily there under PyPy directly passing the ``__call__`` method of a
  28. builtin is also a compatibility issues. Otherwise the functionality is
  29. believed to be uniform between both Python2 and Python3.
  30. Issues
  31. ``````
  32. Source code for ``funcsigs`` is hosted on `GitHub`_. Any bug reports or feature
  33. requests can be made using GitHub's `issues system`_. |build_status| |coverage|
  34. Example
  35. -------
  36. To obtain a `Signature` object, pass the target function to the
  37. ``funcsigs.signature`` function.
  38. .. code-block:: python
  39. >>> from funcsigs import signature
  40. >>> def foo(a, b=None, *args, **kwargs):
  41. ... pass
  42. ...
  43. >>> sig = signature(foo)
  44. >>> sig
  45. <funcsigs.Signature object at 0x...>
  46. >>> sig.parameters
  47. OrderedDict([('a', <Parameter at 0x... 'a'>), ('b', <Parameter at 0x... 'b'>), ('args', <Parameter at 0x... 'args'>), ('kwargs', <Parameter at 0x... 'kwargs'>)])
  48. >>> sig.return_annotation
  49. <class 'funcsigs._empty'>
  50. Introspecting callables with the Signature object
  51. -------------------------------------------------
  52. .. note::
  53. This section of documentation is a direct reproduction of the Python
  54. standard library documentation for the inspect module.
  55. The Signature object represents the call signature of a callable object and its
  56. return annotation. To retrieve a Signature object, use the :func:`signature`
  57. function.
  58. .. function:: signature(callable)
  59. Return a :class:`Signature` object for the given ``callable``::
  60. >>> from funcsigs import signature
  61. >>> def foo(a, *, b:int, **kwargs):
  62. ... pass
  63. >>> sig = signature(foo)
  64. >>> str(sig)
  65. '(a, *, b:int, **kwargs)'
  66. >>> str(sig.parameters['b'])
  67. 'b:int'
  68. >>> sig.parameters['b'].annotation
  69. <class 'int'>
  70. Accepts a wide range of python callables, from plain functions and classes to
  71. :func:`functools.partial` objects.
  72. .. note::
  73. Some callables may not be introspectable in certain implementations of
  74. Python. For example, in CPython, built-in functions defined in C provide
  75. no metadata about their arguments.
  76. .. class:: Signature
  77. A Signature object represents the call signature of a function and its return
  78. annotation. For each parameter accepted by the function it stores a
  79. :class:`Parameter` object in its :attr:`parameters` collection.
  80. Signature objects are *immutable*. Use :meth:`Signature.replace` to make a
  81. modified copy.
  82. .. attribute:: Signature.empty
  83. A special class-level marker to specify absence of a return annotation.
  84. .. attribute:: Signature.parameters
  85. An ordered mapping of parameters' names to the corresponding
  86. :class:`Parameter` objects.
  87. .. attribute:: Signature.return_annotation
  88. The "return" annotation for the callable. If the callable has no "return"
  89. annotation, this attribute is set to :attr:`Signature.empty`.
  90. .. method:: Signature.bind(*args, **kwargs)
  91. Create a mapping from positional and keyword arguments to parameters.
  92. Returns :class:`BoundArguments` if ``*args`` and ``**kwargs`` match the
  93. signature, or raises a :exc:`TypeError`.
  94. .. method:: Signature.bind_partial(*args, **kwargs)
  95. Works the same way as :meth:`Signature.bind`, but allows the omission of
  96. some required arguments (mimics :func:`functools.partial` behavior.)
  97. Returns :class:`BoundArguments`, or raises a :exc:`TypeError` if the
  98. passed arguments do not match the signature.
  99. .. method:: Signature.replace(*[, parameters][, return_annotation])
  100. Create a new Signature instance based on the instance replace was invoked
  101. on. It is possible to pass different ``parameters`` and/or
  102. ``return_annotation`` to override the corresponding properties of the base
  103. signature. To remove return_annotation from the copied Signature, pass in
  104. :attr:`Signature.empty`.
  105. ::
  106. >>> def test(a, b):
  107. ... pass
  108. >>> sig = signature(test)
  109. >>> new_sig = sig.replace(return_annotation="new return anno")
  110. >>> str(new_sig)
  111. "(a, b) -> 'new return anno'"
  112. .. class:: Parameter
  113. Parameter objects are *immutable*. Instead of modifying a Parameter object,
  114. you can use :meth:`Parameter.replace` to create a modified copy.
  115. .. attribute:: Parameter.empty
  116. A special class-level marker to specify absence of default values and
  117. annotations.
  118. .. attribute:: Parameter.name
  119. The name of the parameter as a string. Must be a valid python identifier
  120. name (with the exception of ``POSITIONAL_ONLY`` parameters, which can have
  121. it set to ``None``).
  122. .. attribute:: Parameter.default
  123. The default value for the parameter. If the parameter has no default
  124. value, this attribute is set to :attr:`Parameter.empty`.
  125. .. attribute:: Parameter.annotation
  126. The annotation for the parameter. If the parameter has no annotation,
  127. this attribute is set to :attr:`Parameter.empty`.
  128. .. attribute:: Parameter.kind
  129. Describes how argument values are bound to the parameter. Possible values
  130. (accessible via :class:`Parameter`, like ``Parameter.KEYWORD_ONLY``):
  131. +------------------------+----------------------------------------------+
  132. | Name | Meaning |
  133. +========================+==============================================+
  134. | *POSITIONAL_ONLY* | Value must be supplied as a positional |
  135. | | argument. |
  136. | | |
  137. | | Python has no explicit syntax for defining |
  138. | | positional-only parameters, but many built-in|
  139. | | and extension module functions (especially |
  140. | | those that accept only one or two parameters)|
  141. | | accept them. |
  142. +------------------------+----------------------------------------------+
  143. | *POSITIONAL_OR_KEYWORD*| Value may be supplied as either a keyword or |
  144. | | positional argument (this is the standard |
  145. | | binding behaviour for functions implemented |
  146. | | in Python.) |
  147. +------------------------+----------------------------------------------+
  148. | *VAR_POSITIONAL* | A tuple of positional arguments that aren't |
  149. | | bound to any other parameter. This |
  150. | | corresponds to a ``*args`` parameter in a |
  151. | | Python function definition. |
  152. +------------------------+----------------------------------------------+
  153. | *KEYWORD_ONLY* | Value must be supplied as a keyword argument.|
  154. | | Keyword only parameters are those which |
  155. | | appear after a ``*`` or ``*args`` entry in a |
  156. | | Python function definition. |
  157. +------------------------+----------------------------------------------+
  158. | *VAR_KEYWORD* | A dict of keyword arguments that aren't bound|
  159. | | to any other parameter. This corresponds to a|
  160. | | ``**kwargs`` parameter in a Python function |
  161. | | definition. |
  162. +------------------------+----------------------------------------------+
  163. Example: print all keyword-only arguments without default values::
  164. >>> def foo(a, b, *, c, d=10):
  165. ... pass
  166. >>> sig = signature(foo)
  167. >>> for param in sig.parameters.values():
  168. ... if (param.kind == param.KEYWORD_ONLY and
  169. ... param.default is param.empty):
  170. ... print('Parameter:', param)
  171. Parameter: c
  172. .. method:: Parameter.replace(*[, name][, kind][, default][, annotation])
  173. Create a new Parameter instance based on the instance replaced was invoked
  174. on. To override a :class:`Parameter` attribute, pass the corresponding
  175. argument. To remove a default value or/and an annotation from a
  176. Parameter, pass :attr:`Parameter.empty`.
  177. ::
  178. >>> from funcsigs import Parameter
  179. >>> param = Parameter('foo', Parameter.KEYWORD_ONLY, default=42)
  180. >>> str(param)
  181. 'foo=42'
  182. >>> str(param.replace()) # Will create a shallow copy of 'param'
  183. 'foo=42'
  184. >>> str(param.replace(default=Parameter.empty, annotation='spam'))
  185. "foo:'spam'"
  186. .. class:: BoundArguments
  187. Result of a :meth:`Signature.bind` or :meth:`Signature.bind_partial` call.
  188. Holds the mapping of arguments to the function's parameters.
  189. .. attribute:: BoundArguments.arguments
  190. An ordered, mutable mapping (:class:`collections.OrderedDict`) of
  191. parameters' names to arguments' values. Contains only explicitly bound
  192. arguments. Changes in :attr:`arguments` will reflect in :attr:`args` and
  193. :attr:`kwargs`.
  194. Should be used in conjunction with :attr:`Signature.parameters` for any
  195. argument processing purposes.
  196. .. note::
  197. Arguments for which :meth:`Signature.bind` or
  198. :meth:`Signature.bind_partial` relied on a default value are skipped.
  199. However, if needed, it is easy to include them.
  200. ::
  201. >>> def foo(a, b=10):
  202. ... pass
  203. >>> sig = signature(foo)
  204. >>> ba = sig.bind(5)
  205. >>> ba.args, ba.kwargs
  206. ((5,), {})
  207. >>> for param in sig.parameters.values():
  208. ... if param.name not in ba.arguments:
  209. ... ba.arguments[param.name] = param.default
  210. >>> ba.args, ba.kwargs
  211. ((5, 10), {})
  212. .. attribute:: BoundArguments.args
  213. A tuple of positional arguments values. Dynamically computed from the
  214. :attr:`arguments` attribute.
  215. .. attribute:: BoundArguments.kwargs
  216. A dict of keyword arguments values. Dynamically computed from the
  217. :attr:`arguments` attribute.
  218. The :attr:`args` and :attr:`kwargs` properties can be used to invoke
  219. functions::
  220. def test(a, *, b):
  221. ...
  222. sig = signature(test)
  223. ba = sig.bind(10, b=20)
  224. test(*ba.args, **ba.kwargs)
  225. .. seealso::
  226. :pep:`362` - Function Signature Object.
  227. The detailed specification, implementation details and examples.
  228. Copyright
  229. ---------
  230. *funcsigs* is a derived work of CPython under the terms of the `PSF License
  231. Agreement`_. The original CPython inspect module, its unit tests and
  232. documentation are the copyright of the Python Software Foundation. The derived
  233. work is distributed under the `Apache License Version 2.0`_.
  234. .. _PSF License Agreement: http://docs.python.org/3/license.html#terms-and-conditions-for-accessing-or-otherwise-using-python
  235. .. _Apache License Version 2.0: http://opensource.org/licenses/Apache-2.0
  236. .. _GitHub: https://github.com/testing-cabal/funcsigs
  237. .. _PSF License Agreement: http://docs.python.org/3/license.html#terms-and-conditions-for-accessing-or-otherwise-using-python
  238. .. _Travis CI: http://travis-ci.org/
  239. .. _Read The Docs: http://funcsigs.readthedocs.org/
  240. .. _PEP 362: http://www.python.org/dev/peps/pep-0362/
  241. .. _inspect: http://docs.python.org/3/library/inspect.html#introspecting-callables-with-the-signature-object
  242. .. _issues system: https://github.com/testing-cabal/funcsigs/issues
  243. .. |build_status| image:: https://secure.travis-ci.org/aliles/funcsigs.png?branch=master
  244. :target: http://travis-ci.org/#!/aliles/funcsigs
  245. :alt: Current build status
  246. .. |coverage| image:: https://coveralls.io/repos/aliles/funcsigs/badge.png?branch=master
  247. :target: https://coveralls.io/r/aliles/funcsigs?branch=master
  248. :alt: Coverage status
  249. .. |pypi_version| image:: https://pypip.in/v/funcsigs/badge.png
  250. :target: https://crate.io/packages/funcsigs/
  251. :alt: Latest PyPI version