pax_global_header00006660000000000000000000000064135243605640014522gustar00rootroot0000000000000052 comment=248fe6327a5be58f0dd1797f34ecc96217bd2259 deprecation-2.0.7/000077500000000000000000000000001352436056400140255ustar00rootroot00000000000000deprecation-2.0.7/.coveragerc000066400000000000000000000000511352436056400161420ustar00rootroot00000000000000[run] branch = True source = deprecation deprecation-2.0.7/.gitignore000066400000000000000000000020251352436056400160140ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject deprecation-2.0.7/.travis.yml000066400000000000000000000005031352436056400161340ustar00rootroot00000000000000language: python python: - "2.7" - "3.5" - "3.6" - "3.7-dev" # 3.7 development branch - "pypy" - "pypy3" # command to install dependencies install: "pip install -r test-requirements.txt" # command to run tests script: python -m unittest discover after_success: - coverage run -m unittest discover - codecov deprecation-2.0.7/LICENSE000066400000000000000000000261351352436056400150410ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. deprecation-2.0.7/MANIFEST.in000066400000000000000000000000561352436056400155640ustar00rootroot00000000000000include LICENSE include tests/*.py graft docs deprecation-2.0.7/README.rst000066400000000000000000000064501352436056400155210ustar00rootroot00000000000000deprecation =========== .. image:: https://readthedocs.org/projects/deprecation/badge/?version=latest :target: http://deprecation.readthedocs.io/en/latest/ :alt: Documentation Status .. image:: https://travis-ci.org/briancurtin/deprecation.svg?branch=master :target: https://travis-ci.org/briancurtin/deprecation .. image:: https://codecov.io/gh/briancurtin/deprecation/branch/master/graph/badge.svg :target: https://codecov.io/gh/briancurtin/deprecation The ``deprecation`` library provides a ``deprecated`` decorator and a ``fail_if_not_removed`` decorator for your tests. Together, the two enable the automation of several things: 1. The docstring of a deprecated method gets the deprecation details appended to the end of it. If you generate your API docs direct from your source, you don't need to worry about writing your own notification. You also don't need to worry about forgetting to write it. It's done for you. 2. Rather than having code live on forever because you only deprecated it but never actually moved on from it, you can have your tests tell you when it's time to remove the code. The ``@deprecated`` decorator can be told when it's time to entirely remove the code, which causes ``@fail_if_not_removed`` to raise an ``AssertionError``, causing either your unittest or py.test tests to fail. See http://deprecation.readthedocs.io/ for the full documentation. Installation ============ :: pip install deprecation Usage ===== :: import deprecation @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the bar function instead") def foo(): """Do some stuff""" return 1 ...but doesn't Python ignore ``DeprecationWarning``? ==================================================== Yes, by default since 2.7—and for good reason [#]_ —and this works fine with that. 1. It often makes sense for you to run your tests with a ``-W`` flag or the ``PYTHONWARNINGS`` environment variable so you catch warnings in development and handle them appropriately. The warnings raised by this library show up there, as they're subclasses of the built-in ``DeprecationWarning``. See the `Command Line `_ and `Environment Variable `_ documentation for more details. 2. Even if you don't enable those things, the behavior of this library remains the same. The docstrings will still be updated and the tests will still fail when they need to. You'll get the benefits regardless of what Python cares about ``DeprecationWarning``. ---- .. [#] Exposing application users to ``DeprecationWarning``\s that are emitted by lower-level code needlessly involves end-users in "how things are done." It often leads to users raising issues about warnings they're presented, which on one hand is done rightfully so, as it's been presented to them as some sort of issue to resolve. However, at the same time, the warning could be well known and planned for. From either side, loud ``DeprecationWarning``\s can be seen as noise that isn't necessary outside of development. deprecation-2.0.7/deprecation.py000066400000000000000000000275741352436056400167130ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import collections import functools import textwrap import warnings from packaging import version __version__ = "2.0.7" # This is mostly here so automodule docs are ordered more ideally. __all__ = ["deprecated", "message_location", "fail_if_not_removed", "DeprecatedWarning", "UnsupportedWarning"] #: Location where the details are added to a deprecated docstring #: #: When set to ``"bottom"``, the details are appended to the end. #: When set to ``"top"``, the details are inserted between the #: summary line and docstring contents. message_location = "bottom" class DeprecatedWarning(DeprecationWarning): """A warning class for deprecated methods This is a specialization of the built-in :class:`DeprecationWarning`, adding parameters that allow us to get information into the __str__ that ends up being sent through the :mod:`warnings` system. The attributes aren't able to be retrieved after the warning gets raised and passed through the system as only the class--not the instance--and message are what gets preserved. :param function: The function being deprecated. :param deprecated_in: The version that ``function`` is deprecated in :param removed_in: The version that ``function`` gets removed in :param details: Optional details about the deprecation. Most often this will include directions on what to use instead of the now deprecated code. """ def __init__(self, function, deprecated_in, removed_in, details=""): # NOTE: The docstring only works for this class if it appears up # near the class name, not here inside __init__. I think it has # to do with being an exception class. self.function = function self.deprecated_in = deprecated_in self.removed_in = removed_in self.details = details super(DeprecatedWarning, self).__init__(function, deprecated_in, removed_in, details) def __str__(self): # Use a defaultdict to give us the empty string # when a part isn't included. parts = collections.defaultdict(str) parts["function"] = self.function if self.deprecated_in: parts["deprecated"] = " as of %s" % self.deprecated_in if self.removed_in: parts["removed"] = " and will be removed in %s" % self.removed_in if any([self.deprecated_in, self.removed_in, self.details]): parts["period"] = "." if self.details: parts["details"] = " %s" % self.details return ("%(function)s is deprecated%(deprecated)s%(removed)s" "%(period)s%(details)s" % (parts)) class UnsupportedWarning(DeprecatedWarning): """A warning class for methods to be removed This is a subclass of :class:`~deprecation.DeprecatedWarning` and is used to output a proper message about a function being unsupported. Additionally, the :func:`~deprecation.fail_if_not_removed` decorator will handle this warning and cause any tests to fail if the system under test uses code that raises this warning. """ def __str__(self): parts = collections.defaultdict(str) parts["function"] = self.function parts["removed"] = self.removed_in if self.details: parts["details"] = " %s" % self.details return ("%(function)s is unsupported as of %(removed)s." "%(details)s" % (parts)) def deprecated(deprecated_in=None, removed_in=None, current_version=None, details=""): """Decorate a function to signify its deprecation This function wraps a method that will soon be removed and does two things: * The docstring of the method will be modified to include a notice about deprecation, e.g., "Deprecated since 0.9.11. Use foo instead." * Raises a :class:`~deprecation.DeprecatedWarning` via the :mod:`warnings` module, which is a subclass of the built-in :class:`DeprecationWarning`. Note that built-in :class:`DeprecationWarning`\s are ignored by default, so for users to be informed of said warnings they will need to enable them--see the :mod:`warnings` module documentation for more details. :param deprecated_in: The version at which the decorated method is considered deprecated. This will usually be the next version to be released when the decorator is added. The default is **None**, which effectively means immediate deprecation. If this is not specified, then the `removed_in` and `current_version` arguments are ignored. :param removed_in: The version when the decorated method will be removed. The default is **None**, specifying that the function is not currently planned to be removed. Note: This cannot be set to a value if `deprecated_in=None`. :param current_version: The source of version information for the currently running code. This will usually be a `__version__` attribute on your library. The default is `None`. When `current_version=None` the automation to determine if the wrapped function is actually in a period of deprecation or time for removal does not work, causing a :class:`~deprecation.DeprecatedWarning` to be raised in all cases. :param details: Extra details to be added to the method docstring and warning. For example, the details may point users to a replacement method, such as "Use the foo_bar method instead". By default there are no details. """ # You can't just jump to removal. It's weird, unfair, and also makes # building up the docstring weird. if deprecated_in is None and removed_in is not None: raise TypeError("Cannot set removed_in to a value " "without also setting deprecated_in") # Only warn when it's appropriate. There may be cases when it makes sense # to add this decorator before a formal deprecation period begins. # In CPython, PendingDeprecatedWarning gets used in that period, # so perhaps mimick that at some point. is_deprecated = False is_unsupported = False # StrictVersion won't take a None or a "", so make whatever goes to it # is at least *something*. if current_version: current_version = version.parse(current_version) if (removed_in and current_version >= version.parse(removed_in)): is_unsupported = True elif (deprecated_in and current_version >= version.parse(deprecated_in)): is_deprecated = True else: # If we can't actually calculate that we're in a period of # deprecation...well, they used the decorator, so it's deprecated. # This will cover the case of someone just using # @deprecated("1.0") without the other advantages. is_deprecated = True should_warn = any([is_deprecated, is_unsupported]) def _function_wrapper(function): if should_warn: # Everything *should* have a docstring, but just in case... existing_docstring = function.__doc__ or "" # The various parts of this decorator being optional makes for # a number of ways the deprecation notice could go. The following # makes for a nicely constructed sentence with or without any # of the parts. parts = { "deprecated_in": " %s" % deprecated_in if deprecated_in else "", "removed_in": "\n This will be removed in %s." % removed_in if removed_in else "", "details": " %s" % details if details else ""} deprecation_note = (".. deprecated::{deprecated_in}" "{removed_in}{details}".format(**parts)) # default location for insertion of deprecation note loc = 1 # split docstring at first occurrence of newline string_list = existing_docstring.split("\n", 1) if len(string_list) > 1: # With a multi-line docstring, when we modify # existing_docstring to add our deprecation_note, # if we're not careful we'll interfere with the # indentation levels of the contents below the # first line, or as PEP 257 calls it, the summary # line. Since the summary line can start on the # same line as the """, dedenting the whole thing # won't help. Split the summary and contents up, # dedent the contents independently, then join # summary, dedent'ed contents, and our # deprecation_note. # in-place dedent docstring content string_list[1] = textwrap.dedent(string_list[1]) # we need another newline string_list.insert(loc, "\n") # change the message_location if we add to end of docstring # do this always if not "top" if message_location != "top": loc = 3 # insert deprecation note and dual newline string_list.insert(loc, deprecation_note) string_list.insert(loc, "\n\n") function.__doc__ = "".join(string_list) @functools.wraps(function) def _inner(*args, **kwargs): if should_warn: if is_unsupported: cls = UnsupportedWarning else: cls = DeprecatedWarning the_warning = cls(function.__name__, deprecated_in, removed_in, details) warnings.warn(the_warning, category=DeprecationWarning, stacklevel=2) return function(*args, **kwargs) return _inner return _function_wrapper def fail_if_not_removed(method): """Decorate a test method to track removal of deprecated code This decorator catches :class:`~deprecation.UnsupportedWarning` warnings that occur during testing and causes unittests to fail, making it easier to keep track of when code should be removed. :raises: :class:`AssertionError` if an :class:`~deprecation.UnsupportedWarning` is raised while running the test method. """ # NOTE(briancurtin): Unless this is named test_inner, nose won't work # properly. See Issue #32. def test_inner(*args, **kwargs): with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") rv = method(*args, **kwargs) for warning in caught_warnings: if warning.category == UnsupportedWarning: raise AssertionError( ("%s uses a function that should be removed: %s" % (method, str(warning.message)))) return rv return test_inner deprecation-2.0.7/docs-requirements.txt000066400000000000000000000000121352436056400202300ustar00rootroot00000000000000unittest2 deprecation-2.0.7/docs/000077500000000000000000000000001352436056400147555ustar00rootroot00000000000000deprecation-2.0.7/docs/Makefile000066400000000000000000000011401352436056400164110ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SPHINXPROJ = deprecation SOURCEDIR = . BUILDDIR = _build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)deprecation-2.0.7/docs/conf.py000066400000000000000000000115141352436056400162560ustar00rootroot00000000000000#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # deprecation documentation build configuration file, created by # sphinx-quickstart on Fri Jan 13 16:03:40 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. # 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. # import os import sys sys.path.insert(0, os.path.dirname(__file__)) import deprecation # NOQA # -- 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.autodoc', 'sphinx.ext.intersphinx'] intersphinx_mapping = {'python': ('https://docs.python.org/dev', None)} # 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 master toctree document. master_doc = 'index' # General information about the project. project = 'deprecation' copyright = '2017, Brian Curtin' author = 'Brian Curtin' # 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 = deprecation.__version__ # The full version, including alpha/beta/rc tags. release = deprecation.__version__ # 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 # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # 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 = 'nature' # 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 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'] # -- Options for HTMLHelp output ------------------------------------------ # Output file base name for HTML help builder. htmlhelp_basename = 'deprecationdoc' # -- 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, 'deprecation.tex', 'deprecation Documentation', 'Brian Curtin', 'manual'), ] # -- 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, 'deprecation', 'deprecation Documentation', [author], 1) ] # -- 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, 'deprecation', 'deprecation Documentation', author, 'deprecation', 'A library to handle automated deprecations.', 'Miscellaneous'), ] deprecation-2.0.7/docs/index.rst000066400000000000000000000074001352436056400166170ustar00rootroot00000000000000.. deprecation documentation master file, created by sphinx-quickstart on Fri Jan 13 16:03:40 2017. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. ``deprecation`` =============== ``deprecation`` is a library that enables automated deprecations. It offers the :func:`~deprecation.deprecated` decorator to wrap functions, providing proper warnings both in documentation and via Python's :mod:`warnings` system, as well as the :func:`deprecation.fail_if_not_removed` decorator for test methods to ensure that deprecated code is eventually removed. See `API Documentation`_ to jump straight into the options. See the :doc:`sample` page for an example of ``deprecation``'s effect on a module's Sphinx `autodoc `_ generated documentation. Installation ============ :: pip install deprecation Using ``@deprecated`` ===================== To mark a function or method as deprecated, wrap it in the :func:`~deprecation.deprecated` decorator. This does several things for you: 1. The docstring of the wrapped function will have details appended to it from the arguments you set on :func:`~deprecation.deprecated`. This takes care of telling your users not only that the function is deprecated, but can also tell them when it's going away and what they can do in the meantime. 2. In conjunction with the :func:`~deprecation.fail_if_not_removed` decorator it removes the need for any sort of manual tracking of when a sufficiently deprecated piece of code should be removed from the codebase. It causes tests to fail when they contain code which should be removed. :: import deprecation @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the bar function instead") def foo(): """Do some stuff""" return 1 Now look at the docs. If you you generate API documentation from your source like the :doc:`sample` does, you'll see that the a sentence has been appended to a deprecated function's docstring to include information about when the function is deprecated, when it'll be removed, and what you can do instead. For example, run ``help(foo)`` and this is what you'll get: :: Help on function foo in module example: foo() Do some stuff *Deprecated in 1.0, to be removed in 2.0. Use the bar function instead* You can pass varying amounts of detail to this decorator, but note that in most cases it removes the ability to use :func:`~deprecation.fail_if_not_removed`. See the `API Documentation`_ for full details. Using ``@fail_if_not_removed`` ============================== Once you've marked code for deprecation via :func:`~deprecation.deprecated`, you can sit back and relax as most of the work has been done for you. Assuming you've provided sufficient detail to the decorator, you now just wait for your tests to tell you it's time to delete the code in question. If you wrap test methods which use your now deprecated code in :func:`~deprecation.fail_if_not_removed`, the test will fail with a message notifying you that you should remove this code. :: @deprecation.fail_if_not_removed def test_won(self): self.assertEqual(1, won()) Looking at the :doc:`sample` docs, we can see that this function would fail the tests at version 2.0, when it should be removed. The following shows what test output will look like for a failure. :: AssertionError: uses a function that should be removed: who is unsupported as of 2.0. Use the ``one`` function instead API Documentation ================= .. automodule:: deprecation :members: deprecation-2.0.7/docs/sample.py000066400000000000000000000043001352436056400166050ustar00rootroot00000000000000import unittest2 import deprecation __version__ = "1.5" @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the ``one`` function instead") def won(): """This function returns 1""" # Oops, it's one, not won. Let's deprecate this and get it right. return 1 @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the ``multiline_one`` function instead.") def multiline_bottom(): """This function returns 1. Multiline Bottom. Deprecation Note is inserted at the bottom. This is also here to show that multiline docstrings work """ return 1 @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the ``one`` function instead") def uno(): """Esta función regresa 1 This is Spanish for 'This function returns 1' This is also here to show that multiline docstrings work """ return 1 def one(): """This function returns 1""" return 1 @deprecation.deprecated(deprecated_in="1.0", removed_in="1.5", current_version=__version__, details="Why would you ever do this anyway?") def why(): """This isn't necessary""" return None deprecation.message_location = 'top' @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the ``multiline_one`` function instead.") def multiline_top(): """This function returns 1. Multiline Top. Deprecation Note is inserted above this line. This is done via setting ``deprecation.message_location`` to 'top'. This is also here to show that multiline docstrings work """ return 1 class Tests(unittest2.TestCase): @deprecation.fail_if_not_removed def test_won(self): self.assertEqual(1, won()) @deprecation.fail_if_not_removed def test_why(self): self.assertIsNone(why()) def test_one(self): self.assertEqual(1, one()) deprecation-2.0.7/docs/sample.rst000066400000000000000000000003361352436056400167720ustar00rootroot00000000000000:orphan: ``sample`` module ================= The following documents the ``sample`` module to show what documentation looks like when :func:`~deprecation.deprecated` has modified it. .. automodule:: sample :members: deprecation-2.0.7/example.py000066400000000000000000000004151352436056400160320ustar00rootroot00000000000000import deprecation __version__ = "1.5" @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version=__version__, details="Use the bar function instead") def foo(): """Do some stuff""" return 1 deprecation-2.0.7/setup.cfg000066400000000000000000000000341352436056400156430ustar00rootroot00000000000000[bdist_wheel] universal = 1 deprecation-2.0.7/setup.py000066400000000000000000000034541352436056400155450ustar00rootroot00000000000000import io import re from setuptools import setup AUTHOR = "Brian Curtin" EMAIL = "brian@python.org" def _read_file(): with open("deprecation.py", "r") as f: return f.read() FILE = _read_file() def get_version(): match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", FILE, re.M) if match: return match.group(1) raise RuntimeError("Unable to find __version__ string.") setup(name="deprecation", version=get_version(), description="A library to handle automated deprecations", license="Apache 2", url="http://deprecation.readthedocs.io/", author=AUTHOR, author_email=EMAIL, maintainer=AUTHOR, maintainer_email=EMAIL, install_requires=["packaging"], keywords=["deprecation"], long_description=io.open("README.rst", encoding="utf-8").read(), py_modules=["deprecation"], classifiers=[ "Development Status :: 5 - Production/Stable", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules"], project_urls={ "Documentation": "http://deprecation.readthedocs.io/en/latest/", "Source": "https://github.com/briancurtin/deprecation", "Bug Tracker": "https://github.com/briancurtin/deprecation/issues"}, ) deprecation-2.0.7/test-requirements.txt000066400000000000000000000001061352436056400202630ustar00rootroot00000000000000codecov>=2.0 coverage>=4.3 flake8>=3.2 packaging>=16.8 unittest2>=1.1 deprecation-2.0.7/tests/000077500000000000000000000000001352436056400151675ustar00rootroot00000000000000deprecation-2.0.7/tests/__init__.py000066400000000000000000000000001352436056400172660ustar00rootroot00000000000000deprecation-2.0.7/tests/test_deprecation.py000066400000000000000000000223271352436056400211030ustar00rootroot00000000000000# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # As we unfortunately support Python 2.7, it lacks TestCase.subTest which # is in 3.4+ or in unittest2 import unittest2 import warnings import deprecation class Test_deprecated(unittest2.TestCase): def test_args_set_on_base_class(self): args = (1, 2, 3, 4) dw = deprecation.DeprecatedWarning(*args) self.assertEqual(dw.args, args) def test_removing_without_deprecating(self): self.assertRaises(TypeError, deprecation.deprecated, deprecated_in=None, removed_in="1.0") def test_docstring(self): for test in [{"args": {}, "__doc__": "docstring\n\n.. deprecated::"}, {"args": {"deprecated_in": "1.0"}, "__doc__": "docstring\n\n.. deprecated:: 1.0"}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0"}, "__doc__": "docstring\n\n.. deprecated:: 1.0" "\n This will be removed in 2.0."}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0", "details": "some details"}, "__doc__": "docstring\n\n.. deprecated:: 1.0" "\n This will be removed in 2.0. " "some details"}]: with self.subTest(**test): @deprecation.deprecated(**test["args"]) def fn(): """docstring""" self.assertEqual(fn.__doc__, test["__doc__"]) def test_multiline_docstring(self): docstring = "summary line\n\ndetails\nand more details\n" for test in [{"args": {}, "__doc__": "%s\n\n.. deprecated::"}, {"args": {"deprecated_in": "1.0"}, "__doc__": "%s\n\n.. deprecated:: 1.0"}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0"}, "__doc__": "%s\n\n.. deprecated:: 1.0" "\n This will be removed in 2.0."}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0", "details": "some details"}, "__doc__": "%s\n\n.. deprecated:: 1.0" "\n This will be removed in 2.0. " "some details"}]: with self.subTest(**test): @deprecation.deprecated(**test["args"]) def fn(): """summary line details and more details """ self.assertEqual(fn.__doc__, test["__doc__"] % (docstring)) def test_multiline_docstring_top(self): summary = "summary line" content = "\n\ndetails\nand more details\n" for test in [{"args": {}, "__doc__": "%s\n\n.. deprecated::%s"}, {"args": {"deprecated_in": "1.0"}, "__doc__": "%s\n\n.. deprecated:: 1.0%s"}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0"}, "__doc__": "%s\n\n.. deprecated:: 1.0" "\n This will be removed in 2.0.%s"}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0", "details": "some details"}, "__doc__": "%s\n\n.. deprecated:: 1.0" "\n This will be removed in 2.0. " "some details%s"}]: with self.subTest(**test): deprecation.message_location = "top" @deprecation.deprecated(**test["args"]) def fn(): """summary line details and more details """ self.assertEqual(fn.__doc__, test["__doc__"] % (summary, content)) def test_multiline_fallback(self): docstring = "summary line\n\ndetails\nand more details\n" for test in [{"args": {"deprecated_in": "1.0"}, "__doc__": "%s\n\n.. deprecated:: 1.0"}]: with self.subTest(**test): deprecation.message_location = "pot" @deprecation.deprecated(**test["args"]) def fn(): """summary line details and more details """ self.assertEqual(fn.__doc__, test["__doc__"] % (docstring)) def test_warning_raised(self): ret_val = "lololol" for test in [{"args": {}, # No args just means deprecated "warning": deprecation.DeprecatedWarning, "message": "method is deprecated"}, {"args": {"details": "do something else."}, "warning": deprecation.DeprecatedWarning, "message": "method is deprecated. do something else."}, {"args": {"deprecated_in": "1.0", "current_version": "2.0"}, "warning": deprecation.DeprecatedWarning, "message": "method is deprecated as of 1.0."}, {"args": {"deprecated_in": "1.0", "removed_in": "3.0", "current_version": "2.0"}, "warning": deprecation.DeprecatedWarning, "message": ("method is deprecated as of 1.0 " "and will be removed in 3.0.")}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0", "current_version": "2.0"}, "warning": deprecation.UnsupportedWarning, "message": "method is unsupported as of 2.0."}, {"args": {"deprecated_in": "1.0", "removed_in": "2.0", "current_version": "2.0", "details": "do something else."}, "warning": deprecation.UnsupportedWarning, "message": ("method is unsupported as of 2.0. " "do something else.")}]: with self.subTest(**test): class Test(object): @deprecation.deprecated(**test["args"]) def method(self): return ret_val with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") sot = Test() self.assertEqual(ret_val, sot.method()) self.assertEqual(len(caught_warnings), 1) self.assertEqual(caught_warnings[0].category, test["warning"]) self.assertEqual(str(caught_warnings[0].message), test["message"]) def test_DeprecatedWarning_not_raised(self): ret_val = "lololol" class Test(object): @deprecation.deprecated(deprecated_in="2.0", removed_in="3.0", current_version="1.0") def method(self): """method docstring""" return ret_val with warnings.catch_warnings(record=True): # If a warning is raised it'll be an exception, so we'll fail. warnings.simplefilter("error") sot = Test() self.assertEqual(sot.method(), ret_val) class Test_fail_if_not_removed(unittest2.TestCase): @deprecation.deprecated(deprecated_in="1.0", current_version="2.0") def _deprecated_method(self): pass @deprecation.deprecated(deprecated_in="1.0", removed_in="2.0", current_version="2.0") def _unsupported_method(self): pass def test_UnsupportedWarning_causes_failure(self): with self.assertRaises(AssertionError): @deprecation.fail_if_not_removed def fn(): self._unsupported_method() fn() def test_DeprecatedWarning_doesnt_fail(self): @deprecation.fail_if_not_removed def fn(): self._deprecated_method() try: fn() except AssertionError: self.fail("A DeprecatedWarning shouldn't cause a failure") @unittest2.expectedFailure @deprecation.fail_if_not_removed def test_literal_UnsupportedWarning(self): self._unsupported_method() @deprecation.fail_if_not_removed def test_literal_DeprecatedWarning(self): self._deprecated_method() deprecation-2.0.7/tox.ini000066400000000000000000000010501352436056400153340ustar00rootroot00000000000000[tox] envlist = py37,py36,py35,py27,pypy3,pypy,flake8 skipsdist = True [testenv] usedevelop = True install_command = pip install -U {opts} {packages} deps = -r{toxinidir}/test-requirements.txt setenv = VIRTUAL_ENV={envdir} PYTHONPATH={envdir} commands = python -m unittest discover [testenv:flake8] commands = flake8 [testenv:coverage] commands = coverage run -m unittest discover coverage html [testenv:docs] deps = Sphinx unittest2 changedir = docs commands = sphinx-build -W -b html -d {envtmpdir}/doctrees . _build/html