pax_global_header00006660000000000000000000000064126315730760014524gustar00rootroot0000000000000052 comment=81ff5309d93d7404c314f647ac7f420372e54071 attrs-15.2.0/000077500000000000000000000000001263157307600127465ustar00rootroot00000000000000attrs-15.2.0/.coveragerc000066400000000000000000000002471263157307600150720ustar00rootroot00000000000000[run] branch = True source = attr [paths] source = src/attr .tox/*/lib/python*/site-packages/attr .tox/pypy/site-packages/attr [report] show_missing = True attrs-15.2.0/.gitignore000066400000000000000000000001021263157307600147270ustar00rootroot00000000000000.tox .coverage* *.pyc *.egg-info docs/_build/ htmlcov dist .cache attrs-15.2.0/.travis.yml000066400000000000000000000013471263157307600150640ustar00rootroot00000000000000sudo: false cache: directories: - $HOME/.cache/pip language: python matrix: include: - python: "2.6" # these are just to make travis's UI a bit prettier env: TOXENV=py26 - python: "2.7" env: TOXENV=py27 - python: "3.3" env: TOXENV=py33 - python: "3.4" env: TOXENV=py34 - python: "3.5" env: TOXENV=py35 - python: "pypy" env: TOXENV=pypy # Meta - python: "3.5" env: TOXENV=flake8 - python: "2.7" env: TOXENV=manifest - python: "2.7" env: TOXENV=docs install: - pip install tox script: - tox --hashseed 0 before_install: - pip install codecov after_success: - tox -e coverage-report - codecov notifications: email: false attrs-15.2.0/CHANGELOG.rst000066400000000000000000000020131263157307600147630ustar00rootroot00000000000000Changelog ========= Versions are year-based with a strict backwards compatibility policy. The third digit is only for regressions. 15.2.0 (2015-12-08) ------------------- Changes: ^^^^^^^^ - Add a ``convert`` argument to ``attr.ib``, which allows specifying a function to run on arguments. This allows for simple type conversions, e.g. with ``attr.ib(convert=int)``. `[26] `_ - Speed up object creation when attribute validators are used. `[28] `_ 15.1.0 (2015-08-20) ------------------- Changes: ^^^^^^^^ - Add ``attr.validators.optional`` that wraps other validators allowing attributes to be ``None``. `[16] `_ - Fix multi-level inheritance. `[24] `_ - Fix ``__repr__`` to work for non-redecorated subclasses. `[20] `_ 15.0.0 (2015-04-15) ------------------- Changes: ^^^^^^^^ Initial release. attrs-15.2.0/CODE_OF_CONDUCT.rst000066400000000000000000000045551263157307600157660ustar00rootroot00000000000000Contributor Code of Conduct =========================== As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery * Personal attacks * Trolling or insulting/derogatory comments * Public or private harassment * Publishing other's private information, such as physical or electronic addresses, without explicit permission * Other unethical or unprofessional conduct Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting a project maintainer at hs@ox.cx. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. Maintainers are obligated to maintain confidentiality with regard to the reporter of an incident. This Code of Conduct is adapted from the `Contributor Covenant `_, version 1.3.0, available at `http://contributor-covenant.org/version/1/3/0/ `_. .. _homepage: http://contributor-covenant.org .. _version: http://contributor-covenant.org/version/1/3/0/ attrs-15.2.0/CONTRIBUTING.rst000066400000000000000000000043421263157307600154120ustar00rootroot00000000000000How To Contribute ================= Every open source project lives from the generous help by contributors that sacrifice their time and ``attrs`` is no different. Here are a few guidelines to get you started: - Try to limit each pull request to one change only. - To run the test suite, all you need is a recent tox_. It will ensure the test suite runs with all dependencies against all Python versions just as it will on `Travis CI`_. If you lack some Python version, you can can always limit the environments like ``tox -e py27,py35`` (in that case you may want to look into pyenv_ that makes it very easy to install many different Python versions in parallel). - Make sure your changes pass our CI. You won't get any feedback until it's green unless you ask for it. - If your change is noteworthy, add an entry to the changelog_. Use present tense, semantic newlines, and add link to your pull request. - No contribution is too small; please submit as many fixes for typos and grammar bloopers as you can! - Don’t break `backward compatibility`_. - *Always* add tests and docs for your code. This is a hard rule; patches with missing tests or documentation won’t be merged. - Write `good test docstrings`_. - Obey `PEP 8`_ and `PEP 257`_. - If you address review feedback, make sure to bump the pull request. Maintainers don’t receive notifications if you push new commits. Please note that this project is released with a Contributor `Code of Conduct`_. By participating in this project you agree to abide by its terms. Please report any harm to `Hynek Schlawack `_ in any way you find appropriate. Thank you for considering to contribute to ``attrs``! .. _me: https://hynek.me/about/ .. _`PEP 8`: https://www.python.org/dev/peps/pep-0008/ .. _`PEP 257`: https://www.python.org/dev/peps/pep-0257/ .. _`good test docstrings`: https://jml.io/pages/test-docstrings.html .. _`Code of Conduct`: https://github.com/hynek/attrs/blob/master/CODE_OF_CONDUCT.rst .. _changelog: https://github.com/hynek/attrs/blob/master/CHANGELOG.rst .. _`backward compatibility`: https://attrs.readthedocs.org/en/latest/backward-compatibility.html .. _`tox`: https://testrun.org/tox/ .. _`Travis CI`: https://travis-ci.org/ .. _pyenv: https://github.com/yyuu/pyenv attrs-15.2.0/LICENSE000066400000000000000000000020721263157307600137540ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Hynek Schlawack Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. attrs-15.2.0/MANIFEST.in000066400000000000000000000002761263157307600145110ustar00rootroot00000000000000include *.rst *.txt LICENSE tox.ini .travis.yml docs/Makefile .coveragerc conftest.py recursive-include tests *.py recursive-include docs *.rst recursive-include docs *.py prune docs/_build attrs-15.2.0/README.rst000066400000000000000000000040471263157307600144420ustar00rootroot00000000000000====================================== attrs: Attributes without boilerplate. ====================================== .. image:: https://travis-ci.org/hynek/attrs.svg :target: https://travis-ci.org/hynek/attrs :alt: CI status .. image:: https://codecov.io/github/hynek/attrs/coverage.svg?branch=master :target: https://codecov.io/github/hynek/attrs?branch=master :alt: Coverage .. teaser-begin ``attrs`` is an `MIT `_-licensed Python package with class decorators that ease the chores of implementing the most common attribute-related object protocols: .. code-block:: pycon >>> import attr >>> @attr.s ... class C(object): ... x = attr.ib(default=42) ... y = attr.ib(default=attr.Factory(list)) >>> i = C(x=1, y=2) >>> i C(x=1, y=2) >>> i == C(1, 2) True >>> i != C(2, 1) True >>> attr.asdict(i) {'y': 2, 'x': 1} >>> C() C(x=42, y=[]) >>> C2 = attr.make_class("C2", ["a", "b"]) >>> C2("foo", "bar") C2(a='foo', b='bar') (If you don’t like the playful ``attr.s`` and ``attr.ib``, you can also use their no-nonsense aliases ``attr.attributes`` and ``attr.attr``). You just specify the attributes to work with and ``attrs`` gives you: - a nice human-readable ``__repr__``, - a complete set of comparison methods, - an initializer, - and much more *without* writing dull boilerplate code again and again. This gives you the power to use actual classes with actual types in your code instead of confusing ``tuple``\ s or confusingly behaving ``namedtuple``\ s. So put down that type-less data structures and welcome some class into your life! .. note:: I wrote an `explanation `_ on why I forked my own ``characteristic``. It's not dead but ``attrs`` will have more new features. ``attrs``\ ’s documentation lives at `Read the Docs `_, the code on `GitHub `_. It’s rigorously tested on Python 2.6, 2.7, 3.3+, and PyPy. attrs-15.2.0/conftest.py000066400000000000000000000005351263157307600151500ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function import pytest @pytest.fixture(scope="session") def C(): """ Return a simple but fully features attrs class with an x and a y attribute. """ from attr import attributes, attr @attributes class C(object): x = attr() y = attr() return C attrs-15.2.0/docs/000077500000000000000000000000001263157307600136765ustar00rootroot00000000000000attrs-15.2.0/docs/Makefile000066400000000000000000000151461263157307600153450ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/attrs.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/attrs.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/attrs" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/attrs" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." attrs-15.2.0/docs/api.rst000066400000000000000000000137321263157307600152070ustar00rootroot00000000000000.. _api: API === .. currentmodule:: attr ``attrs`` works by decorating a class using :func:`attr.s` and then optionally defining attributes on the class using :func:`attr.ib`. .. note:: When this documentation speaks about "``attrs`` attributes" it means those attributes that are defined using :func:`attr.ib` in the class body. What follows is the API explanation, if you'd like a more hands-on introduction, have a look at :doc:`examples`. Core ---- .. autofunction:: attr.s(these=None, repr_ns=None, repr=True, cmp=True, hash=True, init=True) .. note:: ``attrs`` also comes with a less playful alias ``attr.attributes``. For example: .. doctest:: >>> import attr >>> @attr.s ... class C(object): ... _private = attr.ib() >>> C(private=42) C(_private=42) >>> class D(object): ... def __init__(self, x): ... self.x = x >>> D(1) >>> D = attr.s(these={"x": attr.ib()}, init=False)(D) >>> D(1) D(x=1) .. autofunction:: attr.ib .. note:: ``attrs`` also comes with a less playful alias ``attr.attr``. .. autoclass:: attr.Attribute Instances of this class are frequently used for introspection purposes like: - Class attributes on ``attrs``-decorated classes *after* ``@attr.s`` has been applied. - :func:`fields` returns a tuple of them. - Validators get them passed as the first argument. .. warning:: You should never instantiate this class yourself! .. doctest:: >>> import attr >>> @attr.s ... class C(object): ... x = attr.ib() >>> C.x Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None) .. autofunction:: attr.make_class This is handy if you want to programmatically create classes. For example: .. doctest:: >>> C1 = attr.make_class("C1", ["x", "y"]) >>> C1(1, 2) C1(x=1, y=2) >>> C2 = attr.make_class("C2", {"x": attr.ib(default=42), ... "y": attr.ib(default=attr.Factory(list))}) >>> C2() C2(x=42, y=[]) .. autoclass:: attr.Factory For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(default=attr.Factory(list)) >>> C() C(x=[]) Helpers ------- ``attrs`` comes with a bunch of helper methods that make the work with it easier: .. autofunction:: attr.fields For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> attr.fields(C) (Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None), Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None)) .. autofunction:: attr.has For example: .. doctest:: >>> @attr.s ... class C(object): ... pass >>> attr.has(C) True >>> attr.has(object) False .. autofunction:: attr.asdict For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> attr.asdict(C(1, C(2, 3))) {'y': {'y': 3, 'x': 2}, 'x': 1} ``attrs`` comes with some handy helpers for filtering: .. autofunction:: attr.filters.include .. autofunction:: attr.filters.exclude .. autofunction:: assoc For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> i1 = C(1, 2) >>> i1 C(x=1, y=2) >>> i2 = attr.assoc(i1, y=3) >>> i2 C(x=1, y=3) >>> i1 == i2 False .. autofunction:: validate For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.instance_of(int)) >>> i = C(1) >>> i.x = "1" >>> attr.validate(i) Traceback (most recent call last): ... TypeError: ("'x' must be (got '1' that is a ).", Attribute(name='x', default=NOTHING, validator=>, repr=True, cmp=True, hash=True, init=True), , '1') Validators can be globally disabled if you want to run them only in development and tests but not in production because you fear their performance impact: .. autofunction:: set_run_validators .. autofunction:: get_run_validators .. _api_validators: Validators ---------- ``attrs`` comes with some common validators within the ``attrs.validators`` module: .. autofunction:: attr.validators.instance_of For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.instance_of(int)) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be (got '42' that is a ).", Attribute(name='x', default=NOTHING, validator=>), , '42') >>> C(None) Traceback (most recent call last): ... TypeError: ("'x' must be (got None that is a ).", Attribute(name='x', default=NOTHING, validator=>, repr=True, cmp=True, hash=True, init=True), , None) .. autofunction:: attr.validators.provides .. autofunction:: attr.validators.optional For example: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(int))) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be (got '42' that is a ).", Attribute(name='x', default=NOTHING, validator=>), , '42') >>> C(None) C(x=None) attrs-15.2.0/docs/backward-compatibility.rst000066400000000000000000000014611263157307600210570ustar00rootroot00000000000000Backward Compatibility ====================== .. currentmodule:: attr ``attrs`` has a very strong backward compatibility policy that is inspired by the one of the `Twisted framework `_. Put simply, you shouldn't ever be afraid to upgrade ``attrs`` if you're using its public APIs. If there will ever be need to break compatibility, it will be announced in the :doc:`changelog`, raise deprecation warning for a year before it's finally really broken. .. _exemption: .. warning:: The structure of the :class:`attr.Attribute` class is exempted from this rule. It *will* change in the future since it should be considered read-only, that shouldn't matter. However if you intend to build extensions on top of ``attrs`` you have to anticipate that. attrs-15.2.0/docs/changelog.rst000066400000000000000000000000361263157307600163560ustar00rootroot00000000000000.. include:: ../CHANGELOG.rst attrs-15.2.0/docs/conf.py000066400000000000000000000224571263157307600152070ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # attrs documentation build configuration file, created by # sphinx-quickstart on Sun May 11 16:17:15 2014. # # 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 codecs import datetime import os import re try: import sphinx_rtd_theme except ImportError: sphinx_rtd_theme = None def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ here = os.path.abspath(os.path.dirname(__file__)) with codecs.open(os.path.join(here, *parts), "rb", "utf-8") as f: return f.read() def find_version(*file_paths): """ Build a path from *file_paths* and search for a ``__version__`` string inside. """ version_file = read(*file_paths) version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) if version_match: return version_match.group(1) raise RuntimeError("Unable to find version string.") # 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.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. 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 = u'attrs' year = datetime.date.today().year copyright = u'2015{0}, Hynek Schlawack'.format( u'-{0}'.format(year) if year != 2015 else u"" ) # 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. release = find_version("../src/attr/__init__.py") version = release.rsplit(u".", 1)[0] # The full version, including alpha/beta/rc tags. # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #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 # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. if sphinx_rtd_theme: html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] else: html_theme = "default" # 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 # " v 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 (within the static path) to use as 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 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 # Output file base name for HTML help builder. htmlhelp_basename = 'attrsdoc' # -- 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': '', } # 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 = [ ('index', 'attrs.tex', u'attrs Documentation', u'Hynek Schlawack', '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 = [ ('index', 'attrs', u'attrs Documentation', [u'Hynek Schlawack'], 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 = [ ('index', 'attrs', u'attrs Documentation', u'Hynek Schlawack', 'attrs', '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 # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'https://docs.python.org/2': None} attrs-15.2.0/docs/contributing.rst000066400000000000000000000000641263157307600171370ustar00rootroot00000000000000.. _contributing: .. include:: ../CONTRIBUTING.rst attrs-15.2.0/docs/examples.rst000066400000000000000000000304071263157307600162520ustar00rootroot00000000000000.. _examples: Examples ======== Basics ------ The simplest possible usage would be: .. doctest:: >>> import attr >>> @attr.s ... class Empty(object): ... pass >>> Empty() Empty() >>> Empty() == Empty() True >>> Empty() is Empty() False So in other words: ``attrs`` useful even without actual attributes! But you'll usually want some data on your classes, so let's add some: .. doctest:: >>> @attr.s ... class Coordinates(object): ... x = attr.ib() ... y = attr.ib() These by default, all features are added, so you have immediately a fully functional data class with a nice ``repr`` string and comparison methods. .. doctest:: >>> c1 = Coordinates(1, 2) >>> c1 Coordinates(x=1, y=2) >>> c2 = Coordinates(x=2, y=1) >>> c2 Coordinates(x=2, y=1) >>> c1 == c2 False As shown, the generated ``__init__`` method allows both for positional and keyword arguments. If playful naming turns you off, ``attrs`` comes with no-nonsense aliases: .. doctest:: >>> @attr.attributes ... class SeriousCoordinates(object): ... x = attr.attr() ... y = attr.attr() >>> SeriousCoordinates(1, 2) SeriousCoordinates(x=1, y=2) >>> attr.fields(Coordinates) == attr.fields(SeriousCoordinates) True For private attributes, ``attrs`` will strip the leading underscores for keyword arguments: .. doctest:: >>> @attr.s ... class C(object): ... _x = attr.ib() >>> C(x=1) C(_x=1) An additional way (not unlike ``characteristic``) of defining attributes is supported too. This is useful in times when you want to enhance classes that are not yours (nice ``__repr__`` for Django models anyone?): .. doctest:: >>> class SomethingFromSomeoneElse(object): ... def __init__(self, x): ... self.x = x >>> SomethingFromSomeoneElse = attr.s(these={"x": attr.ib()}, init=False)(SomethingFromSomeoneElse) >>> SomethingFromSomeoneElse(1) SomethingFromSomeoneElse(x=1) Or if you want to use properties: .. doctest:: >>> @attr.s(these={"_x": attr.ib()}) ... class ReadOnlyXSquared(object): ... @property ... def x(self): ... return self._x ** 2 >>> rox = ReadOnlyXSquared(x=5) >>> rox ReadOnlyXSquared(_x=5) >>> rox.x 25 >>> rox.x = 6 Traceback (most recent call last): ... AttributeError: can't set attribute `Sub-classing `_ is bad for you, but ``attrs`` will still do what you'd hope for: .. doctest:: >>> @attr.s ... class A(object): ... a = attr.ib() ... def get_a(self): ... return self.a >>> @attr.s ... class B(object): ... b = attr.ib() >>> @attr.s ... class C(B, A): ... c = attr.ib() >>> i = C(1, 2, 3) >>> i C(a=1, b=2, c=3) >>> i == C(1, 2, 3) True >>> i.get_a() 1 The order of the attributes is defined by the `MRO `_. In Python 3, classes defined within other classes are `detected `_ and reflected in the ``__repr__``. In Python 2 though, it's impossible. Therefore ``@attr.s`` comes with the ``repr_ns`` option to set it manually: .. doctest:: >>> @attr.s ... class C(object): ... @attr.s(repr_ns="C") ... class D(object): ... pass >>> C.D() C.D() ``repr_ns`` works on both Python 2 and 3. On Python 3 is overrides the implicit detection. Converting to Dictionaries -------------------------- When you have a class with data, it often is very convenient to transform that class into a :class:`dict` (for example if you want to serialize it to JSON): .. doctest:: >>> attr.asdict(Coordinates(x=1, y=2)) {'y': 2, 'x': 1} Some fields cannot or should not be transformed. For that, :func:`attr.asdict` offers a callback that decides whether an attribute should be included: .. doctest:: >>> @attr.s ... class UserList(object): ... users = attr.ib() >>> @attr.s ... class User(object): ... email = attr.ib() ... password = attr.ib() >>> attr.asdict(UserList([User("jane@doe.invalid", "s33kred"), ... User("joe@doe.invalid", "p4ssw0rd")]), ... filter=lambda attr, value: attr.name != "password") {'users': [{'email': 'jane@doe.invalid'}, {'email': 'joe@doe.invalid'}]} For the common case where you want to :func:`include ` or :func:`exclude ` certain types or attributes, ``attrs`` ships with a few helpers: .. doctest:: >>> @attr.s ... class User(object): ... login = attr.ib() ... password = attr.ib() ... id = attr.ib() >>> attr.asdict(User("jane", "s33kred", 42), filter=attr.filters.exclude(User.password, int)) {'login': 'jane'} >>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() ... z = attr.ib() >>> attr.asdict(C("foo", "2", 3), filter=attr.filters.include(int, C.x)) {'x': 'foo', 'z': 3} Defaults -------- Sometimes you want to have default values for your initializer. And sometimes you even want mutable objects as default values (ever used accidentally ``def f(arg=[])``?). ``attrs`` has you covered in both cases: .. doctest:: >>> import collections >>> @attr.s ... class Connection(object): ... socket = attr.ib() ... @classmethod ... def connect(cl, db_string): ... # connect somehow to db_string ... return cl(socket=42) >>> @attr.s ... class ConnectionPool(object): ... db_string = attr.ib() ... pool = attr.ib(default=attr.Factory(collections.deque)) ... debug = attr.ib(default=False) ... def get_connection(self): ... try: ... return self.pool.pop() ... except IndexError: ... if self.debug: ... print "New connection!" ... return Connection.connect(self.db_string) ... def free_connection(self, conn): ... if self.debug: ... print "Connection returned!" ... self.pool.appendleft(conn) ... >>> cp = ConnectionPool("postgres://localhost") >>> cp ConnectionPool(db_string='postgres://localhost', pool=deque([]), debug=False) >>> conn = cp.get_connection() >>> conn Connection(socket=42) >>> cp.free_connection(conn) >>> cp ConnectionPool(db_string='postgres://localhost', pool=deque([Connection(socket=42)]), debug=False) More information on why class methods for constructing objects are awesome can be found in this insightful `blog post `_. Validators ---------- Although your initializers should be as dumb as possible, it can come handy to do some kind of validation on the arguments. That's when :func:`attr.ib`\ ’s ``validator`` argument comes into play. A validator is simply a callable that takes three arguments: #. The *instance* that's being validated. #. The *attribute* that it's validating #. and finally the *value* that is passed for it. If the value does not pass the validator's standards, it just raises an appropriate exception. Since the validator runs *after* the instance is initialized, you can refer to other attributes while validating : .. doctest:: >>> def x_smaller_than_y(instance, attribute, value): ... if value >= instance.y: ... raise ValueError("'x' has to be smaller than 'y'!") >>> @attr.s ... class C(object): ... x = attr.ib(validator=x_smaller_than_y) ... y = attr.ib() >>> C(x=3, y=4) C(x=3, y=4) >>> C(x=4, y=3) Traceback (most recent call last): ... ValueError: 'x' has to be smaller than 'y'! ``attrs`` won't intercept your changes to those attributes but you can always call :func:`attr.validate` on any instance to verify, that it's still valid: .. doctest:: >>> i = C(4, 5) >>> i.x = 5 # works, no magic here >>> attr.validate(i) Traceback (most recent call last): ... ValueError: 'x' has to be smaller than 'y'! ``attrs`` ships with a bunch of validators, make sure to :ref:`check them out ` before writing your own: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.instance_of(int)) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be (got '42' that is a ).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=>), , '42') If you like `zope.interface `_, ``attrs`` also comes with a :func:`attr.validators.provides` validator: .. doctest:: >>> import zope.interface >>> class IFoo(zope.interface.Interface): ... def f(): ... """A function called f.""" >>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.provides(IFoo)) >>> C(x=object()) Traceback (most recent call last): ... TypeError: ("'x' must provide which doesn't.", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=>), , ) >>> @zope.interface.implementer(IFoo) ... @attr.s ... class Foo(object): ... def f(self): ... print("hello, world") >>> C(Foo()) C(x=Foo()) You can also disable them globally: >>> attr.set_run_validators(False) >>> C(42) C(x=42) >>> attr.set_run_validators(True) >>> C(42) Traceback (most recent call last): ... TypeError: ("'x' must provide which 42 doesn't.", Attribute(name='x', default=NOTHING, validator=>, repr=True, cmp=True, hash=True, init=True), , 42) Conversion ---------- Attributes can have a ``convert`` function specified, which will be called with the attribute's passed-in value to get a new value to use. This can be useful for doing type-conversions on values that you don't want to force your callers to do. .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(convert=int) >>> o = C("1") >>> o.x 1 Converters are run *before* validators, so you can use validators to check the final form of the value. .. doctest:: >>> def validate_x(instance, attribute, value): ... if value < 0: ... raise ValueError("x must be be at least 0.") >>> @attr.s ... class C(object): ... x = attr.ib(convert=int, validator=validate_x) >>> o = C("0") >>> o.x 0 >>> C("-1") Traceback (most recent call last): ... ValueError: x must be be at least 0. Other Goodies ------------- Do you like Rich Hickey? I'm glad to report that Clojure's core feature is part of ``attrs``: `assoc `_! I guess that means Clojure can be shut down now, sorry Rich! .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib() ... y = attr.ib() >>> i1 = C(1, 2) >>> i1 C(x=1, y=2) >>> i2 = attr.assoc(i1, y=3) >>> i2 C(x=1, y=3) >>> i1 == i2 False Sometimes you may want to create a class programmatically. ``attrs`` won't let you down: .. doctest:: >>> @attr.s ... class C1(object): ... x = attr.ib() ... y = attr.ib() >>> C2 = attr.make_class("C2", ["x", "y"]) >>> attr.fields(C1) == attr.fields(C2) True You can still have power over the attributes if you pass a dictionary of name: ``attr.ib`` mappings and can pass arguments to ``@attr.s``: .. doctest:: >>> C = attr.make_class("C", {"x": attr.ib(default=42), ... "y": attr.ib(default=attr.Factory(list))}, ... repr=False) >>> i = C() >>> i # no repr added! >>> i.x 42 >>> i.y [] Finally, you can exclude single attributes from certain methods: .. doctest:: >>> @attr.s ... class C(object): ... user = attr.ib() ... password = attr.ib(repr=False) >>> C("me", "s3kr3t") C(user='me') attrs-15.2.0/docs/extending.rst000066400000000000000000000016701263157307600164210ustar00rootroot00000000000000.. _extending: Extending ========= Each ``attrs``-decorated class has a ``__attrs_attrs__`` class attribute. It is a tuple of :class:`attr.Attribute` carrying meta-data about each attribute. So it is fairly simple to build your own decorators on top of ``attrs``: .. doctest:: >>> import attr >>> def print_attrs(cl): ... print cl.__attrs_attrs__ >>> @print_attrs ... @attr.s ... class C(object): ... a = attr.ib() (Attribute(name='a', default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None),) .. warning:: The :func:`attr.s` decorator **must** be applied first because it puts ``__attrs_attrs__`` in place! That means that is has to come *after* your decorator because:: @a @b def f(): pass is just `syntactic sugar `_ for:: def original_f(): pass f = a(b(original_f)) attrs-15.2.0/docs/index.rst000066400000000000000000000010011263157307600155270ustar00rootroot00000000000000attrs: Attributes without boilerplate. ============================================= Release v\ |release| (:doc:`What's new? `). .. include:: ../README.rst :start-after: teaser-begin User's Guide ------------ .. toctree:: :maxdepth: 1 why examples api extending Project Information ------------------- .. toctree:: :maxdepth: 1 backward-compatibility license contributing changelog Indices and tables ================== * :ref:`genindex` * :ref:`search` attrs-15.2.0/docs/license.rst000066400000000000000000000017711263157307600160600ustar00rootroot00000000000000License and Hall of Fame ======================== ``attrs`` is licensed under the `MIT `_ license. The full license text can be also found in the `source code repository `_. Authors ------- ``attrs`` is written and maintained by `Hynek Schlawack `_. The development is kindly supported by `Variomedia AG `_. A full list of contributors can be found in `GitHub's overview `_. It’s the spiritual successor of `characteristic `_ and aspires to fix some of it clunkiness and unfortunate decisions. Both were inspired by Twisted’s `FancyEqMixin `_ but both are implemented using class decorators because `sub-classing is bad for you `_, m’kay? attrs-15.2.0/docs/why.rst000066400000000000000000000155241263157307600152460ustar00rootroot00000000000000.. _why: Why not… ======== …tuples? -------- Readability ^^^^^^^^^^^ What makes more sense while debugging:: Point(x=1, x=2) or:: (1, 2) ? Let's add even more ambiguity:: Customer(id=42, reseller=23, first_name="Jane", last_name="John") or:: (42, 23, "Jane", "John") ? Why would you want to write ``customer[2]`` instead of ``customer.first_name``? Don't get me started when you add nesting. If you've never ran into mysterious tuples you had no idea what the hell they meant while debugging, you're much smarter then I am. Using proper classes with names and types makes program code much more readable and comprehensible_. Especially when trying to grok a new piece of software or returning to old code after several months. .. _comprehensible: http://arxiv.org/pdf/1304.5257.pdf Extendability ^^^^^^^^^^^^^ Imagine you have a function that takes or returns a tuple. Especially if you use tuple unpacking (eg. ``x, y = get_point()``), adding additional data means that you have to change the invocation of that function *everywhere*. Adding an attribute to a class concerns only those who actually care about that attribute. …namedtuples? ------------- The difference between :func:`collections.namedtuple`\ s and classes decorated by ``attrs`` is that the latter are type-sensitive and less typing aside regular classes: .. doctest:: >>> import attr >>> @attr.s ... class C1(object): ... a = attr.ib() ... def print_a(self): ... print self.a >>> @attr.s ... class C2(object): ... a = attr.ib() >>> c1 = C1(a=1) >>> c2 = C2(a=1) >>> c1.a == c2.a True >>> c1 == c2 False >>> c1.print_a() 1 …while namedtuple’s purpose is *explicitly* to behave like tuples: .. doctest:: >>> from collections import namedtuple >>> NT1 = namedtuple("NT1", "a") >>> NT2 = namedtuple("NT2", "b") >>> t1 = NT1._make([1,]) >>> t2 = NT2._make([1,]) >>> t1 == t2 == (1,) True This can easily lead to surprising and unintended behaviors. Other than that, ``attrs`` also adds nifty features like validators or default values. .. _tuple: https://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences …hand-written classes? ---------------------- While I'm a fan of all things artisanal, writing the same nine methods all over again doesn't qualify for me. I usually manage to get some typos inside and there's simply more code that can break and thus has to be tested. To bring it into perspective, the equivalent of .. doctest:: >>> @attr.s ... class SmartClass(object): ... a = attr.ib() ... b = attr.ib() >>> SmartClass(1, 2) SmartClass(a=1, b=2) is .. doctest:: >>> class ArtisanalClass(object): ... def __init__(self, a, b): ... self.a = a ... self.b = b ... ... def __repr__(self): ... return "ArtisanalClass(a={}, b={})".format(self.a, self.b) ... ... def __eq__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) == (other.a, other.b) ... else: ... return NotImplemented ... ... def __ne__(self, other): ... result = self.__eq__(other) ... if result is NotImplemented: ... return NotImplemented ... else: ... return not result ... ... def __lt__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) < (other.a, other.b) ... else: ... return NotImplemented ... ... def __le__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) <= (other.a, other.b) ... else: ... return NotImplemented ... ... def __gt__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) > (other.a, other.b) ... else: ... return NotImplemented ... ... def __ge__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) >= (other.a, other.b) ... else: ... return NotImplemented ... ... def __hash__(self): ... return hash((self.a, self.b)) >>> ArtisanalClass(a=1, b=2) ArtisanalClass(a=1, b=2) which is quite a mouthful and it doesn't even use any of ``attrs``'s more advanced features like validators or defaults values. Also: no tests whatsoever. And who will guarantee you, that you don't accidentally flip the ``<`` in your tenth implementation of ``__gt__``? If you don't care and like typing, I'm not gonna stop you. But if you ever get sick of the repetitiveness, ``attrs`` will be waiting for you. :) …characteristic --------------- `characteristic `_ is a very similar and fairly popular project of mine. So why the self-fork? Basically after nearly a year of usage I ran into annoyances and regretted certain decisions I made early-on to make too many people happy. In the end, *I* wasn't happy using it anymore. So I learned my lesson and ``attrs`` is the result of that. .. note:: Nevertheless, ``characteristic`` is **not** dead. A lot of software uses it and I will keep maintaining it. Reasons For Forking ^^^^^^^^^^^^^^^^^^^ - Fixing those aforementioned annoyances would introduce more complexity. More complexity means more bugs. - Certain unused features make other common features complicated or impossible. Prime example is the ability write your own initializers and make the generated one cooperate with it. The new logic is much simpler allowing for writing optimal initializers. - I want it to be possible to gradually move from ``characteristic`` to ``attrs``. A peaceful co-existence is much easier if it's separate packages altogether. - My libraries have very strict backward-compatibility policies and it would take years to get rid of those annoyances while they shape the implementation of other features. - The name is tooo looong. Main Differences ^^^^^^^^^^^^^^^^ - The attributes are defined *within* the class definition such that code analyzers know about their existence. This is useful in IDEs like PyCharm or linters like PyLint. ``attrs``'s classes look much more idiomatic than ``characteristic``'s. Since it's useful to use ``attrs`` with classes you don't control (e.g. Django models), a similar way to ``characteristic``'s is still supported. - The names are held shorter and easy to both type and read. - It is generally more opinionated towards typical uses. This ensures I'll not wake up in a year hating to use it. - The generated ``__init__`` methods are faster because of certain features that have been left out intentionally. The generated code should be as fast as hand-written one. attrs-15.2.0/setup.cfg000066400000000000000000000001401263157307600145620ustar00rootroot00000000000000[pytest] minversion = 2.8 strict = true addopts = -ra testpaths = tests [wheel] universal = 1 attrs-15.2.0/setup.py000066400000000000000000000047131263157307600144650ustar00rootroot00000000000000import codecs import os import re from setuptools import setup, find_packages ############################################################################### NAME = "attrs" PACKAGES = find_packages(where="src") META_PATH = os.path.join("src", "attr", "__init__.py") KEYWORDS = ["class", "attribute", "boilerplate"] CLASSIFIERS = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Natural Language :: English", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Libraries :: Python Modules", ] INSTALL_REQUIRES = [] ############################################################################### HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read() META_FILE = read(META_PATH) def find_meta(meta): """ Extract __*meta*__ from META_FILE. """ meta_match = re.search( r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M ) if meta_match: return meta_match.group(1) raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) if __name__ == "__main__": setup( name=NAME, description=find_meta("description"), license=find_meta("license"), url=find_meta("uri"), version=find_meta("version"), author=find_meta("author"), author_email=find_meta("email"), maintainer=find_meta("author"), maintainer_email=find_meta("email"), keywords=KEYWORDS, long_description=read("README.rst") + "\n\n" + read("CHANGELOG.rst"), packages=PACKAGES, package_dir={"": "src"}, zip_safe=False, classifiers=CLASSIFIERS, install_requires=INSTALL_REQUIRES, ) attrs-15.2.0/src/000077500000000000000000000000001263157307600135355ustar00rootroot00000000000000attrs-15.2.0/src/attr/000077500000000000000000000000001263157307600145075ustar00rootroot00000000000000attrs-15.2.0/src/attr/__init__.py000066400000000000000000000017001263157307600166160ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function from ._funcs import ( asdict, assoc, has, ) from ._make import ( Attribute, Factory, NOTHING, attr, attributes, fields, make_class, validate, ) from ._config import ( get_run_validators, set_run_validators, ) from . import filters from . import validators __version__ = "15.2.0" __title__ = "attrs" __description__ = "Attributes without boilerplate." __uri__ = "https://attrs.readthedocs.org/" __author__ = "Hynek Schlawack" __email__ = "hs@ox.cx" __license__ = "MIT" __copyright__ = "Copyright (c) 2015 Hynek Schlawack" s = attributes attr = ib = attr __all__ = [ "Attribute", "Factory", "NOTHING", "asdict", "assoc", "attr", "attributes", "fields", "filters", "get_run_validators", "has", "ib", "make_class", "s", "set_run_validators", "validate", "validators", ] attrs-15.2.0/src/attr/_compat.py000066400000000000000000000010311263157307600164760ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function import sys PY3 = sys.version_info[0] == 3 PY2 = sys.version_info[0] == 2 if PY2: # TYPE is used in exceptions, repr(int) is different on Python 2 and 3. TYPE = "type" def exec_(code, locals_, globals_): exec("exec code in locals_, globals_") def iteritems(d): return d.iteritems() else: TYPE = "class" def exec_(code, locals_, globals_): exec(code, locals_, globals_) def iteritems(d): return d.items() attrs-15.2.0/src/attr/_config.py000066400000000000000000000010021263157307600164560ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function __all__ = ["set_run_validators", "get_run_validators"] _run_validators = True def set_run_validators(run): """ Set whether or not validators are run. By default, they are run. """ if not isinstance(run, bool): raise TypeError("'run' must be bool.") global _run_validators _run_validators = run def get_run_validators(): """ Return whether or not validators are run. """ return _run_validators attrs-15.2.0/src/attr/_funcs.py000066400000000000000000000051451263157307600163430ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function import copy from ._compat import iteritems from ._make import Attribute, NOTHING, fields def asdict(inst, recurse=True, filter=None): """ Return the ``attrs`` attribute values of *i* as a dict. Optionally recurse into other ``attrs``-decorated classes. :param inst: Instance of a ``attrs``-decorated class. :param recurse: Recurse into classes that are also ``attrs``-decorated. :type recurse: bool :param filter: A callable whose return code deteremines whether an attribute or element is included (``True``) or dropped (``False``). Is called with the :class:`attr.Attribute` as the first argument and the value as the second argument. :type filer: callable :rtype: :class:`dict` """ attrs = fields(inst.__class__) rv = {} for a in attrs: v = getattr(inst, a.name) if filter is not None and not filter(a, v): continue if recurse is True: if has(v.__class__): rv[a.name] = asdict(v, recurse=True, filter=filter) elif isinstance(v, (tuple, list, set)): rv[a.name] = [ asdict(i, recurse=True, filter=filter) if has(i.__class__) else i for i in v ] elif isinstance(v, dict): rv[a.name] = dict((asdict(kk) if has(kk.__class__) else kk, asdict(vv) if has(vv.__class__) else vv) for kk, vv in iteritems(v)) else: rv[a.name] = v else: rv[a.name] = v return rv def has(cl): """ Check whether *cl* is a class with ``attrs`` attributes. :param cl: Class to introspect. :type cl: type :raise TypeError: If *cl* is not a class. :rtype: :class:`bool` """ try: fields(cl) except ValueError: return False else: return True def assoc(inst, **changes): """ Copy *inst* and apply *changes*. :param inst: Instance of a class with ``attrs`` attributes. :param changes: Keyword changes in the new copy. :return: A copy of inst with *changes* incorporated. """ new = copy.copy(inst) for k, v in iteritems(changes): a = getattr(new.__class__, k, NOTHING) if a is NOTHING or not isinstance(a, Attribute): raise ValueError( "{k} is not an attrs attribute on {cl}." .format(k=k, cl=new.__class__) ) setattr(new, k, v) return new attrs-15.2.0/src/attr/_make.py000066400000000000000000000415031263157307600161400ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function import copy import hashlib import inspect import linecache from ._compat import exec_, iteritems from . import _config class _Nothing(object): """ Sentinel class to indicate the lack of a value when ``None`` is ambiguous. All instances of `_Nothing` are equal. """ def __copy__(self): return self def __deepcopy__(self, _): return self def __eq__(self, other): return self.__class__ == _Nothing def __ne__(self, other): return not self == other def __repr__(self): return "NOTHING" def __hash__(self): return 0xdeadbeef NOTHING = _Nothing() """ Sentinel to indicate the lack of a value when ``None`` is ambiguous. """ def attr(default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None): """ Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with :func:`attr.s`! :param default: Value that is used if an ``attrs``-generated ``__init__`` is used and no value is passed while instantiating. If the value an instance of :class:`Factory`, it callable will be use to construct a new value (useful for mutable datatypes like lists or dicts). :type default: Any value. :param callable validator: :func:`callable` that is called by ``attrs``-generated ``__init__`` methods after the instance has been initialized. They receive the initialized instance, the :class:`Attribute`, and the passed value. The return value is *not* inspected so the validator has to throw an exception itself. They can be globally disabled and re-enabled using :func:`get_run_validators`. :param bool repr: Include this attribute in the generated ``__repr__`` method. :param bool cmp: Include this attribute in the generated comparison methods (``__eq__`` et al). :param bool hash: Include this attribute in the generated ``__hash__`` method. :param bool init: Include this attribute in the generated ``__init__`` method. :param callable convert: :func:`callable` that is called by ``attrs``-generated ``__init__`` methods to convert attribute's value to the desired format. It is given the passed-in value, and the returned value will be used as the new value of the attribute. The value is converted before being passed to the validator, if any. """ return _CountingAttr( default=default, validator=validator, repr=repr, cmp=cmp, hash=hash, init=init, convert=convert, ) def _transform_attrs(cl, these): """ Transforms all `_CountingAttr`s on a class into `Attribute`s and saves the list as a tuple in `__attrs_attrs__`. If *these* is passed, use that and don't look for them on the class. """ super_cls = [] for c in reversed(cl.__mro__[1:-1]): sub_attrs = getattr(c, "__attrs_attrs__", None) if sub_attrs is not None: super_cls.extend(a for a in sub_attrs if a not in super_cls) if these is None: ca_list = [(name, attr) for name, attr in cl.__dict__.items() if isinstance(attr, _CountingAttr)] else: ca_list = [(name, ca) for name, ca in iteritems(these)] cl.__attrs_attrs__ = tuple(super_cls + [ Attribute.from_counting_attr(name=attr_name, ca=ca) for attr_name, ca in sorted(ca_list, key=lambda e: e[1].counter) ]) had_default = False for a in cl.__attrs_attrs__: if these is None and a not in super_cls: setattr(cl, a.name, a) if had_default is True and a.default is NOTHING: raise ValueError( "No mandatory attributes allowed after an attribute with a " "default value or factory. Attribute in question: {a!r}" .format(a=a) ) elif had_default is False and a.default is not NOTHING: had_default = True def attributes(maybe_cl=None, these=None, repr_ns=None, repr=True, cmp=True, hash=True, init=True): """ A class decorator that adds `dunder `_\ -methods according to the specified attributes using :func:`attr.ib` or the *these* argument. :param these: A dictionary of name to :func:`attr.ib` mappings. This is useful to avoid the definition of your attributes within the class body because you can't (e.g. if you want to add ``__repr__`` methods to Django models) or don't want to (e.g. if you want to use :class:`properties `). If *these* is not `None`, the class body is *ignored*. :type these: class:`dict` of :class:`str` to :func:`attr.ib` :param repr_ns: When using nested classes, there's no way in Python 2 to automatically detect that. Therefore it's possible to set the namespace explicitly for a more meaningful ``repr`` output. :param repr: Create a ``__repr__`` method with a human readable represantation of ``attrs`` attributes.. :type repr: bool :param cmp: Create ``__eq__``, ``__ne__``, ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` methods that compare the class as if it were a tuple of its ``attrs`` attributes. But the attributes are *only* compared, if the type of both classes is *identical*! :type cmp: bool :param hash: Create a ``__hash__`` method that returns the :func:`hash` of a tuple of all ``attrs`` attribute values. :type hash: bool :param init: Create a ``__init__`` method that initialiazes the ``attrs`` attributes. Leading underscores are stripped for the argument name. :type init: bool """ def wrap(cl): if getattr(cl, "__class__", None) is None: raise TypeError("attrs only works with new-style classes.") _transform_attrs(cl, these) if repr is True: cl = _add_repr(cl, ns=repr_ns) if cmp is True: cl = _add_cmp(cl) if hash is True: cl = _add_hash(cl) if init is True: cl = _add_init(cl) return cl # attrs_or class type depends on the usage of the decorator. It's a class # if it's used as `@attributes` but ``None`` if used # as `@attributes()`. if maybe_cl is None: return wrap else: return wrap(maybe_cl) def _attrs_to_tuple(obj, attrs): """ Create a tuple of all values of *obj*'s *attrs*. """ return tuple(getattr(obj, a.name) for a in attrs) def _add_hash(cl, attrs=None): """ Add a hash method to *cl*. """ if attrs is None: attrs = [a for a in cl.__attrs_attrs__ if a.hash] def hash_(self): """ Automatically created by attrs. """ return hash(_attrs_to_tuple(self, attrs)) cl.__hash__ = hash_ return cl def _add_cmp(cl, attrs=None): """ Add comparison methods to *cl*. """ if attrs is None: attrs = [a for a in cl.__attrs_attrs__ if a.cmp] def attrs_to_tuple(obj): """ Save us some typing. """ return _attrs_to_tuple(obj, attrs) def eq(self, other): """ Automatically created by attrs. """ if other.__class__ is self.__class__: return attrs_to_tuple(self) == attrs_to_tuple(other) else: return NotImplemented def ne(self, other): """ Automatically created by attrs. """ result = eq(self, other) if result is NotImplemented: return NotImplemented else: return not result def lt(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) < attrs_to_tuple(other) else: return NotImplemented def le(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) <= attrs_to_tuple(other) else: return NotImplemented def gt(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) > attrs_to_tuple(other) else: return NotImplemented def ge(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) >= attrs_to_tuple(other) else: return NotImplemented cl.__eq__ = eq cl.__ne__ = ne cl.__lt__ = lt cl.__le__ = le cl.__gt__ = gt cl.__ge__ = ge return cl def _add_repr(cl, ns=None, attrs=None): """ Add a repr method to *cl*. """ if attrs is None: attrs = [a for a in cl.__attrs_attrs__ if a.repr] def repr_(self): """ Automatically created by attrs. """ real_cl = self.__class__ if ns is None: qualname = getattr(real_cl, "__qualname__", None) if qualname is not None: class_name = qualname.rsplit(">.", 1)[-1] else: class_name = real_cl.__name__ else: class_name = ns + "." + real_cl.__name__ return "{0}({1})".format( class_name, ", ".join(a.name + "=" + repr(getattr(self, a.name)) for a in attrs) ) cl.__repr__ = repr_ return cl def _add_init(cl): attrs = [a for a in cl.__attrs_attrs__ if a.init] # We cache the generated init methods for the same kinds of attributes. sha1 = hashlib.sha1() sha1.update(repr(attrs).encode("utf-8")) unique_filename = "".format( sha1.hexdigest() ) script = _attrs_to_script(attrs) locs = {} bytecode = compile(script, unique_filename, "exec") attr_dict = dict((a.name, a) for a in attrs) exec_(bytecode, {"NOTHING": NOTHING, "attr_dict": attr_dict, "validate": validate, "_convert": _convert}, locs) init = locs["__init__"] # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename ) cl.__init__ = init return cl def fields(cl): """ Returns the tuple of ``attrs`` attributes for a class. :param cl: Class to introspect. :type cl: class :raise TypeError: If *cl* is not a class. :raise ValueError: If *cl* is not an ``attrs`` class. :rtype: tuple of :class:`attr.Attribute` """ if not inspect.isclass(cl): raise TypeError("Passed object must be a class.") attrs = getattr(cl, "__attrs_attrs__", None) if attrs is None: raise ValueError("{cl!r} is not an attrs-decorated class.".format( cl=cl )) return copy.deepcopy(attrs) def validate(inst): """ Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. """ if _config._run_validators is False: return for a in inst.__class__.__attrs_attrs__: if a.validator is not None: a.validator(inst, a, getattr(inst, a.name)) def _convert(inst): """ Convert all attributes on *inst* that have a converter. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. """ for a in fields(inst.__class__): if a.convert is not None: setattr(inst, a.name, a.convert(getattr(inst, a.name))) def _attrs_to_script(attrs): """ Return a valid Python script of an initializer for *attrs*. """ lines = [] args = [] has_validator = False has_convert = False for a in attrs: if a.validator is not None: has_validator = True if a.convert is not None: has_convert = True attr_name = a.name arg_name = a.name.lstrip("_") if a.default is not NOTHING and not isinstance(a.default, Factory): args.append( "{arg_name}=attr_dict['{attr_name}'].default".format( arg_name=arg_name, attr_name=attr_name, ) ) lines.append("self.{attr_name} = {arg_name}".format( arg_name=arg_name, attr_name=attr_name, )) elif a.default is not NOTHING and isinstance(a.default, Factory): args.append("{arg_name}=NOTHING".format(arg_name=arg_name)) lines.extend("""\ if {arg_name} is not NOTHING: self.{attr_name} = {arg_name} else: self.{attr_name} = attr_dict["{attr_name}"].default.factory()""" .format(attr_name=attr_name, arg_name=arg_name) .split("\n")) else: args.append(arg_name) lines.append("self.{attr_name} = {arg_name}".format( attr_name=attr_name, arg_name=arg_name, )) if has_convert: lines.append("_convert(self)") if has_validator: lines.append("validate(self)") return """\ def __init__(self, {args}): {setters} """.format( args=", ".join(args), setters="\n ".join(lines) if lines else "pass", ) class Attribute(object): """ *Read-only* representation of an attribute. :attribute name: The name of the attribute. Plus *all* arguments of :func:`attr.ib`. """ _attributes = [ "name", "default", "validator", "repr", "cmp", "hash", "init", "convert" ] # we can't use ``attrs`` so we have to cheat a little. _optional = {"convert": None} def __init__(self, **kw): if len(kw) > len(Attribute._attributes): raise TypeError("Too many arguments.") for a in Attribute._attributes: try: setattr(self, a, kw[a]) except KeyError: if a in Attribute._optional: setattr(self, a, self._optional[a]) else: raise TypeError("Missing argument '{arg}'.".format(arg=a)) @classmethod def from_counting_attr(cl, name, ca): return cl(name=name, **dict((k, getattr(ca, k)) for k in Attribute._attributes if k != "name")) _a = [Attribute(name=name, default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True) for name in Attribute._attributes] Attribute = _add_hash( _add_cmp(_add_repr(Attribute, attrs=_a), attrs=_a), attrs=_a ) class _CountingAttr(object): """ Intermediate representation of attributes that uses a counter to preserve the order in which the attributes have been defined. """ __attrs_attrs__ = [ Attribute(name=name, default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True) for name in ("counter", "default", "repr", "cmp", "hash", "init",) ] counter = 0 def __init__(self, default, validator, repr, cmp, hash, init, convert): _CountingAttr.counter += 1 self.counter = _CountingAttr.counter self.default = default self.validator = validator self.repr = repr self.cmp = cmp self.hash = hash self.init = init self.convert = convert _CountingAttr = _add_cmp(_add_repr(_CountingAttr)) @attributes class Factory(object): """ Stores a factory callable. If passed as the default value to :func:`attr.ib`, the factory is used to generate a new value. """ factory = attr() def make_class(name, attrs, **attributes_arguments): """ A quick way to create a new class called *name* with *attrs*. :param name: The name for the new class. :type name: str :param attrs: A list of names or a dictionary of mappings of names to attributes. :type attrs: :class:`list` or :class:`dict` :param attributes_arguments: Passed unmodified to :func:`attr.s`. :return: A new class with *attrs*. :rtype: type """ if isinstance(attrs, dict): cl_dict = attrs elif isinstance(attrs, (list, tuple)): cl_dict = dict((a, attr()) for a in attrs) else: raise TypeError("attrs argument must be a dict or a list.") return attributes(**attributes_arguments)(type(name, (object,), cl_dict)) attrs-15.2.0/src/attr/filters.py000066400000000000000000000021631263157307600165330ustar00rootroot00000000000000""" Commonly useful filters for :func:`attr.asdict`. """ from __future__ import absolute_import, division, print_function import inspect from ._make import Attribute def _split_what(what): """ Returns a tuple of `frozenset`s of classes and attributes. """ return ( frozenset(cl for cl in what if inspect.isclass(cl)), frozenset(cl for cl in what if isinstance(cl, Attribute)), ) def include(*what): """ Whitelist *what*. :param what: What to whitelist. :type what: :class:`list` of :class:`type` or :class:`attr.Attribute` s. :rtype: :class:`callable` """ cls, attrs = _split_what(what) def include_(attribute, value): return value.__class__ in cls or attribute in attrs return include_ def exclude(*what): """ Blacklist *what*. :param what: What to blacklist. :type what: :class:`list` of classes or :class:`attr.Attribute` s. :rtype: :class:`callable` """ cls, attrs = _split_what(what) def exclude_(attribute, value): return value.__class__ not in cls and attribute not in attrs return exclude_ attrs-15.2.0/src/attr/validators.py000066400000000000000000000064671263157307600172460ustar00rootroot00000000000000""" Commonly useful validators. """ from __future__ import absolute_import, division, print_function from ._make import attr, attributes @attributes(repr=False) class _InstanceOfValidator(object): type = attr() def __call__(self, inst, attr, value): """ We use a callable class to be able to change the ``__repr__``. """ if not isinstance(value, self.type): raise TypeError( "'{name}' must be {type!r} (got {value!r} that is a " "{actual!r})." .format(name=attr.name, type=self.type, actual=value.__class__, value=value), attr, self.type, value, ) def __repr__(self): return ( "" .format(type=self.type) ) def instance_of(type): """ A validator that raises a :exc:`TypeError` if the initializer is called with a wrong type for this particular attribute (checks are perfomed using :func:`isinstance`). :param type: The type to check for. :type type: type The :exc:`TypeError` is raised with a human readable error message, the attribute (of type :class:`attr.Attribute`), the expected type and the value it got. """ return _InstanceOfValidator(type) @attributes(repr=False) class _ProvidesValidator(object): interface = attr() def __call__(self, inst, attr, value): """ We use a callable class to be able to change the ``__repr__``. """ if not self.interface.providedBy(value): raise TypeError( "'{name}' must provide {interface!r} which {value!r} " "doesn't." .format(name=attr.name, interface=self.interface, value=value), attr, self.interface, value, ) def __repr__(self): return ( "" .format(interface=self.interface) ) def provides(interface): """ A validator that raises a :exc:`TypeError` if the initializer is called with an object that does not provide the requested *interface* (checks are performed using ``interface.providedBy(value)`` (see `zope.interface `_). :param interface: The interface to check for. :type interface: zope.interface.Interface The :exc:`TypeError` is raised with a human readable error message, the attribute (of type :class:`attr.Attribute`), the expected interface, and the value it got. """ return _ProvidesValidator(interface) @attributes(repr=False) class _OptionalValidator(object): validator = attr() def __call__(self, inst, attr, value): if value is None: return return self.validator(inst, attr, value) def __repr__(self): return ( "" .format(type=repr(self.validator)) ) def optional(validator): """ A validator that makes an attribute optional. An optional attribute is one which can be set to ``None`` in addition to satisfying the requirements of the sub-validator. :param validator: A validator that is used for non-``None`` values. """ return _OptionalValidator(validator) attrs-15.2.0/tests/000077500000000000000000000000001263157307600141105ustar00rootroot00000000000000attrs-15.2.0/tests/__init__.py000066400000000000000000000021001263157307600162120ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function from attr import Attribute from attr._make import NOTHING, make_class def simple_class(cmp=False, repr=False, hash=False): """ Return a new simple class. """ return make_class( "C", ["a", "b"], cmp=cmp, repr=repr, hash=hash, init=True, ) def simple_attr(name, default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True): """ Return an attribute with a name and no other bells and whistles. """ return Attribute( name=name, default=default, validator=validator, repr=repr, cmp=cmp, hash=hash, init=init ) class TestSimpleClass(object): """ Tests for the testing helper function `make_class`. """ def test_returns_class(self): """ Returns a class object. """ assert type is simple_class().__class__ def returns_distinct_classes(self): """ Each call returns a completely new class. """ assert simple_class() is not simple_class() attrs-15.2.0/tests/test_config.py000066400000000000000000000022141263157307600167650ustar00rootroot00000000000000""" Tests for `attr._config`. """ from __future__ import absolute_import, division, print_function import pytest from attr import _config class TestConfig(object): def test_default(self): """ Run validators by default. """ assert True is _config._run_validators def test_set_run_validators(self): """ Sets `_run_validators`. """ _config.set_run_validators(False) assert False is _config._run_validators _config.set_run_validators(True) assert True is _config._run_validators def test_get_run_validators(self): """ Returns `_run_validators`. """ _config._run_validators = False assert _config._run_validators is _config.get_run_validators() _config._run_validators = True assert _config._run_validators is _config.get_run_validators() def test_wrong_type(self): """ Passing anything else than a boolean raises TypeError. """ with pytest.raises(TypeError) as e: _config.set_run_validators("False") assert "'run' must be bool." == e.value.args[0] attrs-15.2.0/tests/test_dark_magic.py000066400000000000000000000055711263157307600176120ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function import pytest import attr from attr._compat import TYPE from attr._make import Attribute, NOTHING @attr.s class C1(object): x = attr.ib(validator=attr.validators.instance_of(int)) y = attr.ib() foo = None @attr.s() class C2(object): x = attr.ib(default=foo) y = attr.ib(default=attr.Factory(list)) @attr.s class Super(object): x = attr.ib() def meth(self): return self.x @attr.s class Sub(Super): y = attr.ib() class TestDarkMagic(object): """ Integration tests. """ def test_fields(self): """ `attr.fields` works. """ assert ( Attribute(name="x", default=foo, validator=None, repr=True, cmp=True, hash=True, init=True), Attribute(name="y", default=attr.Factory(list), validator=None, repr=True, cmp=True, hash=True, init=True), ) == attr.fields(C2) def test_asdict(self): """ `attr.asdict` works. """ assert { "x": 1, "y": 2, } == attr.asdict(C1(x=1, y=2)) def test_validator(self): """ `instance_of` raises `TypeError` on type mismatch. """ with pytest.raises(TypeError) as e: C1("1", 2) assert ( "'x' must be <{type} 'int'> (got '1' that is a <{type} " "'str'>).".format(type=TYPE), C1.x, int, "1", ) == e.value.args def test_renaming(self): """ Private members are renamed but only in `__init__`. """ @attr.s class C3(object): _x = attr.ib() assert "C3(_x=1)" == repr(C3(x=1)) def test_programmatic(self): """ `attr.make_class` works. """ PC = attr.make_class("PC", ["a", "b"]) assert ( Attribute(name="a", default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True), Attribute(name="b", default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True), ) == attr.fields(PC) def test_subclassing_with_extra_attrs(self): """ Sub-classing (where the subclass has extra attrs) does what you'd hope for. """ obj = object() i = Sub(x=obj, y=2) assert i.x is i.meth() is obj assert i.y == 2 assert "Sub(x={obj}, y=2)".format(obj=obj) == repr(i) def test_subclass_without_extra_attrs(self): """ Sub-classing (where the subclass does not have extra attrs) still behaves the same as a subclss with extra attrs. """ class Sub2(Super): pass obj = object() i = Sub2(x=obj) assert i.x is i.meth() is obj assert "Sub2(x={obj})".format(obj=obj) == repr(i) attrs-15.2.0/tests/test_dunders.py000066400000000000000000000172741263157307600172000ustar00rootroot00000000000000""" Tests for dunder methods from `attrib._make`. """ from __future__ import absolute_import, division, print_function import copy import pytest from . import simple_attr, simple_class from attr._make import ( Factory, NOTHING, _Nothing, _add_init, _add_repr, attr, make_class, ) from attr.validators import instance_of CmpC = simple_class(cmp=True) ReprC = simple_class(repr=True) HashC = simple_class(hash=True) class InitC(object): __attrs_attrs__ = [simple_attr("a"), simple_attr("b")] InitC = _add_init(InitC) class TestAddCmp(object): """ Tests for `_add_cmp`. """ def test_cmp(self): """ If `cmp` is False, ignore that attribute. """ C = make_class("C", {"a": attr(cmp=False), "b": attr()}) assert C(1, 2) == C(2, 2) def test_equal(self): """ Equal objects are detected as equal. """ assert CmpC(1, 2) == CmpC(1, 2) assert not (CmpC(1, 2) != CmpC(1, 2)) def test_unequal_same_class(self): """ Unequal objects of correct type are detected as unequal. """ assert CmpC(1, 2) != CmpC(2, 1) assert not (CmpC(1, 2) == CmpC(2, 1)) def test_unequal_different_class(self): """ Unequal objects of differnt type are detected even if their attributes match. """ class NotCmpC(object): a = 1 b = 2 assert CmpC(1, 2) != NotCmpC() assert not (CmpC(1, 2) == NotCmpC()) def test_lt(self): """ __lt__ compares objects as tuples of attribute values. """ for a, b in [ ((1, 2), (2, 1)), ((1, 2), (1, 3)), (("a", "b"), ("b", "a")), ]: assert CmpC(*a) < CmpC(*b) def test_lt_unordable(self): """ __lt__ returns NotImplemented if classes differ. """ assert NotImplemented == (CmpC(1, 2).__lt__(42)) def test_le(self): """ __le__ compares objects as tuples of attribute values. """ for a, b in [ ((1, 2), (2, 1)), ((1, 2), (1, 3)), ((1, 1), (1, 1)), (("a", "b"), ("b", "a")), (("a", "b"), ("a", "b")), ]: assert CmpC(*a) <= CmpC(*b) def test_le_unordable(self): """ __le__ returns NotImplemented if classes differ. """ assert NotImplemented == (CmpC(1, 2).__le__(42)) def test_gt(self): """ __gt__ compares objects as tuples of attribute values. """ for a, b in [ ((2, 1), (1, 2)), ((1, 3), (1, 2)), (("b", "a"), ("a", "b")), ]: assert CmpC(*a) > CmpC(*b) def test_gt_unordable(self): """ __gt__ returns NotImplemented if classes differ. """ assert NotImplemented == (CmpC(1, 2).__gt__(42)) def test_ge(self): """ __ge__ compares objects as tuples of attribute values. """ for a, b in [ ((2, 1), (1, 2)), ((1, 3), (1, 2)), ((1, 1), (1, 1)), (("b", "a"), ("a", "b")), (("a", "b"), ("a", "b")), ]: assert CmpC(*a) >= CmpC(*b) def test_ge_unordable(self): """ __ge__ returns NotImplemented if classes differ. """ assert NotImplemented == (CmpC(1, 2).__ge__(42)) class TestAddRepr(object): """ Tests for `_add_repr`. """ def test_repr(self): """ If `repr` is False, ignore that attribute. """ C = make_class("C", {"a": attr(repr=False), "b": attr()}) assert "C(b=2)" == repr(C(1, 2)) def test_repr_works(self): """ repr returns a sensible value. """ assert "C(a=1, b=2)" == repr(ReprC(1, 2)) def test_underscores(self): """ repr does not strip underscores. """ class C(object): __attrs_attrs__ = [simple_attr("_x")] C = _add_repr(C) i = C() i._x = 42 assert "C(_x=42)" == repr(i) class TestAddHash(object): """ Tests for `_add_hash`. """ def test_hash(self): """ If `hash` is False, ignore that attribute. """ C = make_class("C", {"a": attr(hash=False), "b": attr()}) assert hash(C(1, 2)) == hash(C(2, 2)) def test_hash_works(self): """ __hash__ returns different hashes for different values. """ assert hash(HashC(1, 2)) != hash(HashC(1, 1)) class TestAddInit(object): """ Tests for `_add_init`. """ def test_init(self): """ If `init` is False, ignore that attribute. """ C = make_class("C", {"a": attr(init=False), "b": attr()}) with pytest.raises(TypeError) as e: C(a=1, b=2) assert ( "__init__() got an unexpected keyword argument 'a'" == e.value.args[0] ) def test_sets_attributes(self): """ The attributes are initialized using the passed keywords. """ obj = InitC(a=1, b=2) assert 1 == obj.a assert 2 == obj.b def test_default(self): """ If a default value is present, it's used as fallback. """ class C(object): __attrs_attrs__ = [ simple_attr(name="a", default=2), simple_attr(name="b", default="hallo"), simple_attr(name="c", default=None), ] C = _add_init(C) i = C() assert 2 == i.a assert "hallo" == i.b assert None is i.c def test_factory(self): """ If a default factory is present, it's used as fallback. """ class D(object): pass class C(object): __attrs_attrs__ = [ simple_attr(name="a", default=Factory(list)), simple_attr(name="b", default=Factory(D)), ] C = _add_init(C) i = C() assert [] == i.a assert isinstance(i.b, D) def test_validator(self): """ If a validator is passed, call it with the preliminary instance, the Attribute, and the argument. """ class VException(Exception): pass def raiser(*args): raise VException(*args) C = make_class("C", {"a": attr("a", validator=raiser)}) with pytest.raises(VException) as e: C(42) assert (C.a, 42,) == e.value.args[1:] assert isinstance(e.value.args[0], C) def test_validator_others(self): """ Does not interfere when setting non-attrs attributes. """ C = make_class("C", {"a": attr("a", validator=instance_of(int))}) i = C(1) i.b = "foo" assert 1 == i.a assert "foo" == i.b def test_underscores(self): """ The argument names in `__init__` are without leading and trailing underscores. """ class C(object): __attrs_attrs__ = [simple_attr("_private")] C = _add_init(C) i = C(private=42) assert 42 == i._private class TestNothing(object): """ Tests for `_Nothing`. """ def test_copy(self): """ __copy__ returns the same object. """ n = _Nothing() assert n is copy.copy(n) def test_deepcopy(self): """ __deepcopy__ returns the same object. """ n = _Nothing() assert n is copy.deepcopy(n) def test_eq(self): """ All instances are equal. """ assert _Nothing() == _Nothing() == NOTHING assert not (_Nothing() != _Nothing) attrs-15.2.0/tests/test_filters.py000066400000000000000000000040561263157307600171760ustar00rootroot00000000000000""" Tests for `attr.filters`. """ from __future__ import absolute_import, division, print_function import pytest from attr._make import attributes, attr from attr.filters import _split_what, include, exclude @attributes class C(object): a = attr() b = attr() class TestSplitWhat(object): """ Tests for `_split_what`. """ def test_splits(self): """ Splits correctly. """ assert ( frozenset((int, str)), frozenset((C.a,)), ) == _split_what((str, C.a, int,)) class TestInclude(object): """ Tests for `include`. """ @pytest.mark.parametrize("incl,value", [ ((int,), 42), ((str,), "hello"), ((str, C.a), 42), ((str, C.b), "hello"), ]) def test_allow(self, incl, value): """ Return True if a class or attribute is whitelisted. """ i = include(*incl) assert i(C.a, value) is True @pytest.mark.parametrize("incl,value", [ ((str,), 42), ((int,), "hello"), ((str, C.b), 42), ((int, C.b), "hello"), ]) def test_drop_class(self, incl, value): """ Return False on non-whitelisted classes and attributes. """ i = include(*incl) assert i(C.a, value) is False class TestExclude(object): """ Tests for `exclude`. """ @pytest.mark.parametrize("excl,value", [ ((str,), 42), ((int,), "hello"), ((str, C.b), 42), ((int, C.b), "hello"), ]) def test_allow(self, excl, value): """ Return True if class or attribute is not blacklisted. """ e = exclude(*excl) assert e(C.a, value) is True @pytest.mark.parametrize("excl,value", [ ((int,), 42), ((str,), "hello"), ((str, C.a), 42), ((str, C.b), "hello"), ]) def test_drop_class(self, excl, value): """ Return True on non-blacklisted classes and attributes. """ e = exclude(*excl) assert e(C.a, value) is False attrs-15.2.0/tests/test_funcs.py000066400000000000000000000062211263157307600166400ustar00rootroot00000000000000""" Tests for `attr._funcs`. """ from __future__ import absolute_import, division, print_function import pytest from attr._funcs import ( asdict, assoc, has, ) from attr._make import ( attr, attributes, ) class TestAsDict(object): """ Tests for `asdict`. """ def test_shallow(self, C): """ Shallow asdict returns correct dict. """ assert { "x": 1, "y": 2, } == asdict(C(x=1, y=2), False) def test_recurse(self, C): """ Deep asdict returns correct dict. """ assert { "x": {"x": 1, "y": 2}, "y": {"x": 3, "y": 4}, } == asdict(C( C(1, 2), C(3, 4), )) def test_filter(self, C): """ Attributes that are supposed to be skipped are skipped. """ assert { "x": {"x": 1}, } == asdict(C( C(1, 2), C(3, 4), ), filter=lambda a, v: a.name != "y") @pytest.mark.parametrize("container", [ list, tuple, ]) def test_lists_tuples(self, container, C): """ If recurse is True, also recurse into lists. """ assert { "x": 1, "y": [{"x": 2, "y": 3}, {"x": 4, "y": 5}, "a"], } == asdict(C(1, container([C(2, 3), C(4, 5), "a"]))) def test_dicts(self, C): """ If recurse is True, also recurse into dicts. """ assert { "x": 1, "y": {"a": {"x": 4, "y": 5}}, } == asdict(C(1, {"a": C(4, 5)})) class TestHas(object): """ Tests for `has`. """ def test_positive(self, C): """ Returns `True` on decorated classes. """ assert has(C) def test_positive_empty(self): """ Returns `True` on decorated classes even if there are no attributes. """ @attributes class D(object): pass assert has(D) def test_negative(self): """ Returns `False` on non-decorated classes. """ assert not has(object) class TestAssoc(object): """ Tests for `assoc`. """ def test_empty(self): """ Empty classes without changes get copied. """ @attributes class C(object): pass i1 = C() i2 = assoc(i1) assert i1 is not i2 assert i1 == i2 def test_no_changes(self, C): """ No changes means a verbatim copy. """ i1 = C(1, 2) i2 = assoc(i1) assert i1 is not i2 assert i1 == i2 def test_change(self, C): """ Changes work. """ i = assoc(C(1, 2), x=42) assert C(42, 2) == i def test_unknown(self, C): """ Wanting to change an unknown attribute raises a ValueError. """ @attributes class C(object): x = attr() y = 42 with pytest.raises(ValueError) as e: assoc(C(1), y=2) assert ( "y is not an attrs attribute on {cl!r}.".format(cl=C), ) == e.value.args attrs-15.2.0/tests/test_make.py000066400000000000000000000271141263157307600164430ustar00rootroot00000000000000""" Tests for `attr._make`. """ from __future__ import absolute_import, division, print_function import pytest from . import simple_attr from attr import _config from attr._compat import PY3 from attr._make import ( Attribute, NOTHING, _CountingAttr, _transform_attrs, attr, attributes, fields, make_class, validate, ) class TestCountingAttr(object): """ Tests for `attr`. """ def test_returns_Attr(self): """ Returns an instance of _CountingAttr. """ a = attr() assert isinstance(a, _CountingAttr) def make_tc(): class TransformC(object): z = attr() y = attr() x = attr() a = 42 return TransformC class TestTransformAttrs(object): """ Tests for `_transform_attrs`. """ def test_normal(self): """ Transforms every `_CountingAttr` and leaves others (a) be. """ C = make_tc() _transform_attrs(C, None) assert ["z", "y", "x"] == [a.name for a in C.__attrs_attrs__] def test_empty(self): """ No attributes works as expected. """ @attributes class C(object): pass _transform_attrs(C, None) assert () == C.__attrs_attrs__ @pytest.mark.parametrize("attribute", [ "z", "y", "x", ]) def test_transforms_to_attribute(self, attribute): """ All `_CountingAttr`s are transformed into `Attribute`s. """ C = make_tc() _transform_attrs(C, None) assert isinstance(getattr(C, attribute), Attribute) def test_conflicting_defaults(self): """ Raises `ValueError` if attributes with defaults are followed by mandatory attributes. """ class C(object): x = attr(default=None) y = attr() with pytest.raises(ValueError) as e: _transform_attrs(C, None) assert ( "No mandatory attributes allowed after an attribute with a " "default value or factory. Attribute in question: Attribute" "(name='y', default=NOTHING, validator=None, repr=True, " "cmp=True, hash=True, init=True, convert=None)", ) == e.value.args def test_these(self): """ If these is passed, use it and ignore body. """ class C(object): y = attr() _transform_attrs(C, {"x": attr()}) assert ( simple_attr("x"), ) == C.__attrs_attrs__ assert isinstance(C.y, _CountingAttr) def test_recurse(self): """ Collect attributes from all sub-classes. """ class A(object): a = None class B(A): b = attr() _transform_attrs(B, None) class C(B): c = attr() _transform_attrs(C, None) class D(C): d = attr() _transform_attrs(D, None) class E(D): e = attr() _transform_attrs(E, None) assert ( simple_attr("b"), simple_attr("c"), simple_attr("d"), simple_attr("e"), ) == E.__attrs_attrs__ class TestAttributes(object): """ Tests for the `attributes` class decorator. """ @pytest.mark.skipif(PY3, reason="No old-style classes in Py3") def test_catches_old_style(self): """ Raises TypeError on old-style classes. """ with pytest.raises(TypeError) as e: @attributes class C: pass assert ("attrs only works with new-style classes.",) == e.value.args def test_sets_attrs(self): """ Sets the `__attrs_attrs__` class attribute with a list of `Attribute`s. """ @attributes class C(object): x = attr() assert "x" == C.__attrs_attrs__[0].name assert all(isinstance(a, Attribute) for a in C.__attrs_attrs__) def test_empty(self): """ No attributes, no problems. """ @attributes class C3(object): pass assert "C3()" == repr(C3()) assert C3() == C3() @pytest.mark.parametrize("method_name", [ "__repr__", "__eq__", "__hash__", "__init__", ]) def test_adds_all_by_default(self, method_name): """ If no further arguments are supplied, all add_XXX functions are applied. """ # Set the method name to a sentinel and check whether it has been # overwritten afterwards. sentinel = object() class C1(object): x = attr() setattr(C1, method_name, sentinel) C1 = attributes(C1) class C2(object): x = attr() setattr(C2, method_name, sentinel) C2 = attributes(C2) assert sentinel != getattr(C1, method_name) assert sentinel != getattr(C2, method_name) @pytest.mark.parametrize("arg_name, method_name", [ ("repr", "__repr__"), ("cmp", "__eq__"), ("hash", "__hash__"), ("init", "__init__"), ]) def test_respects_add_arguments(self, arg_name, method_name): """ If a certain `add_XXX` is `True`, XXX is not added to the class. """ # Set the method name to a sentinel and check whether it has been # overwritten afterwards. sentinel = object() am_args = { "repr": True, "cmp": True, "hash": True, "init": True } am_args[arg_name] = False class C(object): x = attr() setattr(C, method_name, sentinel) C = attributes(**am_args)(C) assert sentinel == getattr(C, method_name) @pytest.mark.skipif(not PY3, reason="__qualname__ is PY3-only.") def test_repr_qualname(self): """ On Python 3, the name in repr is the __qualname__. """ @attributes class C(object): @attributes class D(object): pass assert "C.D()" == repr(C.D()) assert "GC.D()" == repr(GC.D()) def test_repr_fake_qualname(self): """ Setting repr_ns overrides a potentially guessed namespace. """ @attributes class C(object): @attributes(repr_ns="C") class D(object): pass assert "C.D()" == repr(C.D()) @attributes class GC(object): @attributes class D(object): pass class TestAttribute(object): """ Tests for `Attribute`. """ def test_missing_argument(self): """ Raises `TypeError` if an Argument is missing. """ with pytest.raises(TypeError) as e: Attribute(default=NOTHING, validator=None) assert ("Missing argument 'name'.",) == e.value.args def test_too_many_arguments(self): """ Raises `TypeError` if extra arguments are passed. """ with pytest.raises(TypeError) as e: Attribute(name="foo", default=NOTHING, factory=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True, convert=None) assert ("Too many arguments.",) == e.value.args class TestMakeClass(object): """ Tests for `make_class`. """ @pytest.mark.parametrize("ls", [ list, tuple ]) def test_simple(self, ls): """ Passing a list of strings creates attributes with default args. """ C1 = make_class("C1", ls(["a", "b"])) @attributes class C2(object): a = attr() b = attr() assert C1.__attrs_attrs__ == C2.__attrs_attrs__ def test_dict(self): """ Passing a dict of name: _CountingAttr creates an equivalent class. """ C1 = make_class("C1", {"a": attr(default=42), "b": attr(default=None)}) @attributes class C2(object): a = attr(default=42) b = attr(default=None) assert C1.__attrs_attrs__ == C2.__attrs_attrs__ def test_attr_args(self): """ attributes_arguments are passed to attributes """ C = make_class("C", ["x"], repr=False) assert repr(C(1)).startswith(" (got '42' that is a <{type} " "'str'>).".format(type=TYPE), a, int, "42", ) == e.value.args def test_repr(self): """ Returned validator has a useful `__repr__`. """ v = instance_of(int) assert ( ">" .format(type=TYPE) ) == repr(v) class IFoo(zope.interface.Interface): """ An interface. """ def f(): """ A function called f. """ class TestProvides(object): """ Tests for `provides`. """ def test_success(self): """ Nothing happens if value provides requested interface. """ @zope.interface.implementer(IFoo) class C(object): def f(self): pass v = provides(IFoo) v(None, simple_attr("x"), C()) def test_fail(self): """ Raises `TypeError` if interfaces isn't provided by value. """ value = object() a = simple_attr("x") v = provides(IFoo) with pytest.raises(TypeError) as e: v(None, a, value) assert ( "'x' must provide {interface!r} which {value!r} doesn't." .format(interface=IFoo, value=value), a, IFoo, value, ) == e.value.args def test_repr(self): """ Returned validator has a useful `__repr__`. """ v = provides(IFoo) assert ( "" .format(interface=IFoo) ) == repr(v) class TestOptional(object): """ Tests for `optional`. """ def test_success_with_type(self): """ Nothing happens if types match. """ v = optional(instance_of(int)) v(None, simple_attr("test"), 42) def test_success_with_none(self): """ Nothing happens if None. """ v = optional(instance_of(int)) v(None, simple_attr("test"), None) def test_fail(self): """ Raises `TypeError` on wrong types. """ v = optional(instance_of(int)) a = simple_attr("test") with pytest.raises(TypeError) as e: v(None, a, "42") assert ( "'test' must be <{type} 'int'> (got '42' that is a <{type} " "'str'>).".format(type=TYPE), a, int, "42", ) == e.value.args def test_repr(self): """ Returned validator has a useful `__repr__`. """ v = optional(instance_of(int)) assert ( ("> or None>") .format(type=TYPE) ) == repr(v) attrs-15.2.0/tox.ini000066400000000000000000000016521263157307600142650ustar00rootroot00000000000000[tox] envlist = coverage-clean,py26,py27,py33,py34,py35,pypy,flake8,manifest,docs,coverage-report [testenv] passenv = TERM # ensure colors deps = coverage pytest zope.interface commands = coverage run --parallel -m pytest {posargs} [testenv:flake8] basepython = python3.5 deps = flake8 commands = flake8 src tests setup.py [testenv:docs] basepython = python2.7 setenv = PYTHONHASHSEED = 0 deps = sphinx zope.interface commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs docs/_build/html sphinx-build -W -b doctest -d {envtmpdir}/doctrees docs docs/_build/html python -m doctest README.rst [testenv:manifest] deps = check-manifest skip_install = true commands = check-manifest [testenv:coverage-clean] deps = coverage skip_install = true commands = coverage erase [testenv:coverage-report] deps = coverage skip_install = true commands = coverage combine coverage report