summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMichele Simionato <michele.simionato@gmail.com>2017-07-23 17:22:43 +0200
committerGitHub <noreply@github.com>2017-07-23 17:22:43 +0200
commit00584a5550de21c1af952c141a6bc272d6020035 (patch)
tree4532907d559ca1bf9bab22e924d77594236eebc9
parenta4b6dc28a709c98f071c8061429840ac371d70a1 (diff)
parent15d908b3ce3db5607c75f7dff052b1541f73f534 (diff)
downloadpython-decorator-git-4.1.2.tar.gz
Merge pull request #43 from micheles/coro-signaturerelease-4.1.24.1.2
Now the coroutine signature is determined by the caller
-rw-r--r--CHANGES.md7
-rw-r--r--docs/conf.py356
-rw-r--r--docs/tests.documentation.rst23
-rw-r--r--src/decorator.py11
-rw-r--r--src/tests/documentation.py19
-rw-r--r--src/tests/test.py13
6 files changed, 414 insertions, 15 deletions
diff --git a/CHANGES.md b/CHANGES.md
index ce2339a..148c1a3 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -3,7 +3,12 @@ HISTORY
## Unreleased
-## 4.1.1 (2017-06-15)
+## 4.1.2 (2017-07-23)
+
+Made it possible to define decorators converting coroutines into regular
+functions, as requested by Itaï Ben Yaacov.
+
+## 4.1.1 (2017-06-16)
Changed the documentation build system to sphinx and uploaded the docs
on readthedocs.org.
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 0000000..5415263
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,356 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#
+# decorator documentation build configuration file, created by
+# sphinx-quickstart on Sun Jul 23 17:11:44 2017.
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys
+import os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration ------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ 'sphinx.ext.viewcode',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+# source_suffix = ['.rst', '.md']
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = 'decorator'
+copyright = '2017, Michele Simionato'
+author = 'Michele Simionato'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = '4.1'
+# The full version, including alpha/beta/rc tags.
+release = '4.1.2'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built documents.
+#keep_warnings = False
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = False
+
+
+# -- Options for HTML output ----------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'alabaster'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (relative to this directory) to use as a favicon of
+# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# Add any extra paths that contain custom files (such as robots.txt or
+# .htaccess) here, relative to this directory. These files are copied
+# directly to the root of the documentation.
+#html_extra_path = []
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Language to be used for generating the HTML full-text search index.
+# Sphinx supports the following languages:
+# 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja'
+# 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr'
+#html_search_language = 'en'
+
+# A dictionary with options for the search language support, empty by default.
+# Now only 'ja' uses this config value
+#html_search_options = {'type': 'default'}
+
+# The name of a javascript file (relative to the configuration directory) that
+# implements a search results scorer. If empty, the default will be used.
+#html_search_scorer = 'scorer.js'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'decoratordoc'
+
+# -- Options for LaTeX output ---------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+
+# Latex figure (float) alignment
+#'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+# author, documentclass [howto, manual, or own class]).
+latex_documents = [
+ (master_doc, 'decorator.tex', 'decorator Documentation',
+ 'Michele Simionato', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output ---------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ (master_doc, 'decorator', 'decorator Documentation',
+ [author], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output -------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ (master_doc, 'decorator', 'decorator Documentation',
+ author, 'decorator', 'One line description of project.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+#texinfo_no_detailmenu = False
+
+
+# -- Options for Epub output ----------------------------------------------
+
+# Bibliographic Dublin Core info.
+epub_title = project
+epub_author = author
+epub_publisher = author
+epub_copyright = copyright
+
+# The basename for the epub file. It defaults to the project name.
+#epub_basename = project
+
+# The HTML theme for the epub output. Since the default themes are not
+# optimized for small screen space, using the same theme for HTML and epub
+# output is usually not wise. This defaults to 'epub', a theme designed to save
+# visual space.
+#epub_theme = 'epub'
+
+# The language of the text. It defaults to the language option
+# or 'en' if the language is not set.
+#epub_language = ''
+
+# The scheme of the identifier. Typical schemes are ISBN or URL.
+#epub_scheme = ''
+
+# The unique identifier of the text. This can be a ISBN number
+# or the project homepage.
+#epub_identifier = ''
+
+# A unique identification for the text.
+#epub_uid = ''
+
+# A tuple containing the cover image and cover page html template filenames.
+#epub_cover = ()
+
+# A sequence of (type, uri, title) tuples for the guide element of content.opf.
+#epub_guide = ()
+
+# HTML files that should be inserted before the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_pre_files = []
+
+# HTML files that should be inserted after the pages created by sphinx.
+# The format is a list of tuples containing the path and title.
+#epub_post_files = []
+
+# A list of files that should not be packed into the epub file.
+epub_exclude_files = ['search.html']
+
+# The depth of the table of contents in toc.ncx.
+#epub_tocdepth = 3
+
+# Allow duplicate toc entries.
+#epub_tocdup = True
+
+# Choose between 'default' and 'includehidden'.
+#epub_tocscope = 'default'
+
+# Fix unsupported image types using the Pillow.
+#epub_fix_images = False
+
+# Scale large images.
+#epub_max_image_width = 0
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#epub_show_urls = 'inline'
+
+# If false, no index is generated.
+#epub_use_index = True
diff --git a/docs/tests.documentation.rst b/docs/tests.documentation.rst
index d05172f..f77cb10 100644
--- a/docs/tests.documentation.rst
+++ b/docs/tests.documentation.rst
@@ -3,9 +3,9 @@ The ``decorator`` module
:Author: Michele Simionato
:E-mail: michele.simionato@gmail.com
-:Version: 4.1.1 (2017-07-16)
+:Version: 4.1.2 (2017-07-23)
:Supports: Python 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6
-:Download page: http://pypi.python.org/pypi/decorator/4.1.1
+:Download page: http://pypi.python.org/pypi/decorator/4.1.2
:Installation: ``pip install decorator``
:License: BSD license
@@ -966,8 +966,23 @@ with a particularly complex chain of coroutines. With a single line you
can decorate the troubling coroutine function, understand what happens, fix the
issue and then remove the decorator (or keep it if continuous monitoring
of the coroutines makes sense). Notice that
-`inspect.iscoroutinefunction(make_task)`
-will return then right answer (i.e. `True`).
+``inspect.iscoroutinefunction(make_task)``
+will return the right answer (i.e. ``True``).
+
+It is also possible to define decorators converting coroutine functions
+into regular functions, such as the following:
+
+.. code-block:: python
+
+ @decorator
+ def coro_to_func(coro, *args, **kw):
+ "Convert a coroutine into a function"
+ return get_event_loop().run_until_complete(coro(*args, **kw))
+
+Notice the diffence: the caller in ``log_start_stop`` was a coroutine
+function and the associate decorator was converting coroutines->coroutines;
+the caller in ``coro_to_func`` is a regular function and converts
+coroutines -> functions.
Multiple dispatch
-------------------------------------------
diff --git a/src/decorator.py b/src/decorator.py
index aa09566..788f4bb 100644
--- a/src/decorator.py
+++ b/src/decorator.py
@@ -40,7 +40,7 @@ import operator
import itertools
import collections
-__version__ = '4.1.1'
+__version__ = '4.1.2'
if sys.version >= '3':
from inspect import getfullargspec
@@ -97,7 +97,6 @@ class FunctionMaker(object):
def __init__(self, func=None, name=None, signature=None,
defaults=None, doc=None, module=None, funcdict=None):
self.shortsignature = signature
- self.coro = False
if func:
# func can be a class or a callable, but not an instance method
self.name = func.__name__
@@ -106,7 +105,6 @@ class FunctionMaker(object):
self.doc = func.__doc__
self.module = func.__module__
if inspect.isfunction(func):
- self.coro = iscoroutinefunction(func)
argspec = getfullargspec(func)
self.annotations = getattr(func, '__annotations__', {})
for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs',
@@ -223,7 +221,8 @@ class FunctionMaker(object):
func = obj
self = cls(func, name, signature, defaults, doc, module)
ibody = '\n'.join(' ' + line for line in body.splitlines())
- if self.coro:
+ caller = evaldict.get('_call_') # when called from `decorate`
+ if caller and iscoroutinefunction(caller):
body = ('async def %(name)s(%(signature)s):\n' + ibody).replace(
'return', 'return await')
else:
@@ -263,9 +262,9 @@ def decorator(caller, _func=None):
else: # assume caller is an object with a __call__ method
name = caller.__class__.__name__.lower()
doc = caller.__call__.__doc__
- evaldict = dict(_call_=caller, _decorate_=decorate)
+ evaldict = dict(_call=caller, _decorate_=decorate)
return FunctionMaker.create(
- '%s(func)' % name, 'return _decorate_(func, _call_)',
+ '%s(func)' % name, 'return _decorate_(func, _call)',
evaldict, doc=doc, module=caller.__module__,
__wrapped__=caller)
diff --git a/src/tests/documentation.py b/src/tests/documentation.py
index 3e1568a..e8fcc55 100644
--- a/src/tests/documentation.py
+++ b/src/tests/documentation.py
@@ -752,8 +752,23 @@ with a particularly complex chain of coroutines. With a single line you
can decorate the troubling coroutine function, understand what happens, fix the
issue and then remove the decorator (or keep it if continuous monitoring
of the coroutines makes sense). Notice that
-`inspect.iscoroutinefunction(make_task)`
-will return then right answer (i.e. `True`).
+``inspect.iscoroutinefunction(make_task)``
+will return the right answer (i.e. ``True``).
+
+It is also possible to define decorators converting coroutine functions
+into regular functions, such as the following:
+
+.. code-block:: python
+
+ @decorator
+ def coro_to_func(coro, *args, **kw):
+ "Convert a coroutine into a function"
+ return get_event_loop().run_until_complete(coro(*args, **kw))
+
+Notice the diffence: the caller in ``log_start_stop`` was a coroutine
+function and the associate decorator was converting coroutines->coroutines;
+the caller in ``coro_to_func`` is a regular function and converts
+coroutines -> functions.
Multiple dispatch
-------------------------------------------
diff --git a/src/tests/test.py b/src/tests/test.py
index d882418..7eb8391 100644
--- a/src/tests/test.py
+++ b/src/tests/test.py
@@ -30,15 +30,25 @@ if sys.version >= '3.5':
async def before_after(coro, *args, **kwargs):
return "<before>" + (await coro(*args, **kwargs)) + "<after>"
+@decorator
+def coro_to_func(coro, *args, **kw):
+ return get_event_loop().run_until_complete(coro(*args, **kw))
class CoroutineTestCase(unittest.TestCase):
- def test(self):
+ def test_before_after(self):
@before_after
async def coro(x):
return x
self.assertTrue(inspect.iscoroutinefunction(coro))
out = get_event_loop().run_until_complete(coro('x'))
self.assertEqual(out, '<before>x<after>')
+
+ def test_coro_to_func(self):
+ @coro_to_func
+ async def coro(x):
+ return x
+ self.assertFalse(inspect.iscoroutinefunction(coro))
+ self.assertEqual(coro('x'), 'x')
''')
@@ -92,7 +102,6 @@ class ExtraTestCase(unittest.TestCase):
@d1
def f1(x, y, z):
pass
-
self.assertNotEqual(d1.__code__.co_filename, d2.__code__.co_filename)
self.assertNotEqual(f1.__code__.co_filename, f2.__code__.co_filename)
self.assertNotEqual(f1_orig.__code__.co_filename,