Bug 1458700: [python] Vendor attrs; r=dustin,ted

Differential Revision: https://phabricator.services.mozilla.com/D1124

--HG--
extra : source : 75ef3b64c1698ec53d1d289201ec9a3d51fea7b1
extra : histedit_source : 53d76ae733322098ca6b8f01fe4c2911c348ac3a
This commit is contained in:
Tom Prince 2018-05-02 19:39:38 -06:00
parent 9be271f7c9
commit 5658bb444e
61 changed files with 10457 additions and 0 deletions

View File

@ -6,6 +6,7 @@ mozilla.pth:python/mozrelease
mozilla.pth:python/mozterm
mozilla.pth:python/mozversioncontrol
mozilla.pth:python/l10n
mozilla.pth:third_party/python/attrs/src
mozilla.pth:third_party/python/blessings
mozilla.pth:third_party/python/compare-locales
mozilla.pth:third_party/python/configobj

13
third_party/python/attrs/.coveragerc vendored Normal file
View File

@ -0,0 +1,13 @@
[run]
branch = True
source =
attr
[paths]
source =
src/attr
.tox/*/lib/python*/site-packages/attr
.tox/pypy/site-packages/attr
[report]
show_missing = True

View File

@ -0,0 +1,55 @@
Contributor Covenant Code of Conduct
====================================
Our Pledge
----------
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
Our Standards
-------------
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
Our Responsibilities
--------------------
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
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.
Scope
-----
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
Representation of a project may be further defined and clarified by project maintainers.
Enforcement
-----------
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team 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.
The project team is obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
Attribution
-----------
This Code of Conduct is adapted from the `Contributor Covenant <https://www.contributor-covenant.org>`_, version 1.4, available at <https://www.contributor-covenant.org/version/1/4/code-of-conduct.html>.

View File

@ -0,0 +1,220 @@
How To Contribute
=================
First off, thank you for considering contributing to ``attrs``!
It's people like *you* who make it such a great tool for everyone.
This document intends to make contribution more accessible by codifying tribal knowledge and expectations.
Don't be afraid to open half-finished PRs, and ask questions if something is unclear!
Support
-------
In case you'd like to help out but don't want to deal with GitHub, there's a great opportunity:
help your fellow developers on `StackOverflow <https://stackoverflow.com/questions/tagged/python-attrs>`_!
The offical tag is ``python-attrs`` and helping out in support frees us up to improve ``attrs`` instead!
Workflow
--------
- No contribution is too small!
Please submit as many fixes for typos and grammar bloopers as you can!
- Try to limit each pull request to *one* change only.
- *Always* add tests and docs for your code.
This is a hard rule; patches with missing tests or documentation can't be merged.
- Make sure your changes pass our CI_.
You won't get any feedback until it's green unless you ask for it.
- Once you've addressed review feedback, make sure to bump the pull request with a short note, so we know you're done.
- Dont break `backward compatibility`_.
Code
----
- Obey `PEP 8`_ and `PEP 257`_.
We use the ``"""``\ -on-separate-lines style for docstrings:
.. code-block:: python
def func(x):
"""
Do something.
:param str x: A very important parameter.
:rtype: str
"""
- If you add or change public APIs, tag the docstring using ``.. versionadded:: 16.0.0 WHAT`` or ``.. versionchanged:: 16.2.0 WHAT``.
- Prefer double quotes (``"``) over single quotes (``'``) unless the string contains double quotes itself.
Tests
-----
- Write your asserts as ``expected == actual`` to line them up nicely:
.. code-block:: python
x = f()
assert 42 == x.some_attribute
assert "foo" == x._a_private_attribute
- 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 versions, you can can always limit the environments like ``tox -e py27,py35`` (in that case you may want to look into pyenv_, which makes it very easy to install many different Python versions in parallel).
- Write `good test docstrings`_.
- To ensure new features work well with the rest of the system, they should be also added to our `Hypothesis`_ testing strategy, which is found in ``tests/strategies.py``.
Documentation
-------------
- Use `semantic newlines`_ in reStructuredText_ files (files ending in ``.rst``):
.. code-block:: rst
This is a sentence.
This is another sentence.
- If you start a new section, add two blank lines before and one blank line after the header, except if two headers follow immediately after each other:
.. code-block:: rst
Last line of previous section.
Header of New Top Section
-------------------------
Header of New Section
^^^^^^^^^^^^^^^^^^^^^
First line of new section.
- If you add a new feature, demonstrate its awesomeness on the `examples page`_!
Changelog
^^^^^^^^^
If your change is noteworthy, there needs to be a changelog entry so our users can learn about it!
To avoid merge conflicts, we use the towncrier_ package to manage our changelog.
``towncrier`` uses independent files for each pull request -- so called *news fragments* -- instead of one monolithic changelog file.
On release, those news fragments are compiled into our ``CHANGELOG.rst``.
You don't need to install ``towncrier`` yourself, you just have to abide by a few simple rules:
- For each pull request, add a new file into ``changelog.d`` with a filename adhering to the ``pr#.(change|deprecation|breaking).rst`` schema:
For example, ``changelog.d/42.change.rst`` for a non-breaking change that is proposed in pull request #42.
- As with other docs, please use `semantic newlines`_ within news fragments.
- Wrap symbols like modules, functions, or classes into double backticks so they are rendered in a monospace font.
- If you mention functions or other callables, add parentheses at the end of their names: ``attr.func()`` or ``attr.Class.method()``.
This makes the changelog a lot more readable.
- Prefer simple past tense or constructions with "now".
For example:
+ Added ``attr.validators.func()``.
+ ``attr.func()`` now doesn't crash the Large Hadron Collider anymore.
- If you want to reference multiple issues, copy the news fragment to another filename.
``towncrier`` will merge all news fragments with identical contents into one entry with multiple links to the respective pull requests.
Example entries:
.. code-block:: rst
Added ``attr.validators.func()``.
The feature really *is* awesome.
or:
.. code-block:: rst
``attr.func()`` now doesn't crash the Large Hadron Collider anymore.
The bug really *was* nasty.
----
``tox -e changelog`` will render the current changelog to the terminal if you have any doubts.
Local Development Environment
-----------------------------
You can (and should) run our test suite using tox_.
However, youll probably want a more traditional environment as well.
We highly recommend to develop using the latest Python 3 release because ``attrs`` tries to take advantage of modern features whenever possible.
First create a `virtual environment <https://virtualenv.pypa.io/>`_.
Its out of scope for this document to list all the ways to manage virtual environments in Python, but if you dont already have a pet way, take some time to look at tools like `pew <https://github.com/berdario/pew>`_, `virtualfish <http://virtualfish.readthedocs.io/>`_, and `virtualenvwrapper <http://virtualenvwrapper.readthedocs.io/>`_.
Next, get an up to date checkout of the ``attrs`` repository:
.. code-block:: bash
$ git checkout git@github.com:python-attrs/attrs.git
Change into the newly created directory and **after activating your virtual environment** install an editable version of ``attrs`` along with its tests and docs requirements:
.. code-block:: bash
$ cd attrs
$ pip install -e .[dev]
At this point,
.. code-block:: bash
$ python -m pytest
should work and pass, as should:
.. code-block:: bash
$ cd docs
$ make html
The built documentation can then be found in ``docs/_build/html/``.
Governance
----------
``attrs`` is maintained by `team of volunteers`_ that is always open to new members that share our vision of a fast, lean, and magic-free library that empowers programmers to write better code with less effort.
If you'd like to join, just get a pull request merged and ask to be added in the very same pull request!
**The simple rule is that everyone is welcome to review/merge pull requests of others but nobody is allowed to merge their own code.**
`Hynek Schlawack`_ acts reluctantly as the BDFL_ and has the final say over design decisions.
****
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 contributing to ``attrs``!
.. _`Hynek Schlawack`: 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/python-attrs/attrs/blob/master/.github/CODE_OF_CONDUCT.rst
.. _changelog: https://github.com/python-attrs/attrs/blob/master/CHANGELOG.rst
.. _`backward compatibility`: http://www.attrs.org/en/latest/backward-compatibility.html
.. _tox: https://tox.readthedocs.io/
.. _pyenv: https://github.com/pyenv/pyenv
.. _reStructuredText: http://www.sphinx-doc.org/en/stable/rest.html
.. _semantic newlines: http://rhodesmill.org/brandon/2012/one-sentence-per-line/
.. _examples page: https://github.com/python-attrs/attrs/blob/master/docs/examples.rst
.. _Hypothesis: https://hypothesis.readthedocs.io/
.. _CI: https://travis-ci.org/python-attrs/attrs/
.. _`team of volunteers`: https://github.com/python-attrs
.. _BDFL: https://en.wikipedia.org/wiki/Benevolent_dictator_for_life
.. _towncrier: https://pypi.org/project/towncrier

View File

@ -0,0 +1,6 @@
---
python:
version: 3
pip_install: true
extra_requirements:
- docs

11
third_party/python/attrs/AUTHORS.rst vendored Normal file
View File

@ -0,0 +1,11 @@
Credits
=======
``attrs`` is written and maintained by `Hynek Schlawack <https://hynek.me/>`_.
The development is kindly supported by `Variomedia AG <https://www.variomedia.de/>`_.
A full list of contributors can be found in `GitHub's overview <https://github.com/python-attrs/attrs/graphs/contributors>`_.
Its the spiritual successor of `characteristic <https://characteristic.readthedocs.io/>`_ and aspires to fix some of it clunkiness and unfortunate decisions.
Both were inspired by Twisteds `FancyEqMixin <https://twistedmatrix.com/documents/current/api/twisted.python.util.FancyEqMixin.html>`_ but both are implemented using class decorators because `sub-classing is bad for you <https://www.youtube.com/watch?v=3MNVP9-hglc>`_, mkay?

471
third_party/python/attrs/CHANGELOG.rst vendored Normal file
View File

@ -0,0 +1,471 @@
Changelog
=========
Versions follow `CalVer <http://calver.org>`_ with a strict backwards compatibility policy.
The third digit is only for regressions.
.. towncrier release notes start
18.1.0 (2018-05-03)
-------------------
Changes
^^^^^^^
- ``x=X(); x.cycle = x; repr(x)`` will no longer raise a ``RecursionError``, and will instead show as ``X(x=...)``.
`#95 <https://github.com/python-attrs/attrs/issues/95>`_
- ``attr.ib(factory=f)`` is now syntactic sugar for the common case of ``attr.ib(default=attr.Factory(f))``.
`#178 <https://github.com/python-attrs/attrs/issues/178>`_,
`#356 <https://github.com/python-attrs/attrs/issues/356>`_
- Added ``attr.field_dict()`` to return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names.
`#290 <https://github.com/python-attrs/attrs/issues/290>`_,
`#349 <https://github.com/python-attrs/attrs/issues/349>`_
- The order of attributes that are passed into ``attr.make_class()`` or the ``these`` argument of ``@attr.s()`` is now retained if the dictionary is ordered (i.e. ``dict`` on Python 3.6 and later, ``collections.OrderedDict`` otherwise).
Before, the order was always determined by the order in which the attributes have been defined which may not be desirable when creating classes programatically.
`#300 <https://github.com/python-attrs/attrs/issues/300>`_,
`#339 <https://github.com/python-attrs/attrs/issues/339>`_,
`#343 <https://github.com/python-attrs/attrs/issues/343>`_
- In slotted classes, ``__getstate__`` and ``__setstate__`` now ignore the ``__weakref__`` attribute.
`#311 <https://github.com/python-attrs/attrs/issues/311>`_,
`#326 <https://github.com/python-attrs/attrs/issues/326>`_
- Setting the cell type is now completely best effort.
This fixes ``attrs`` on Jython.
We cannot make any guarantees regarding Jython though, because our test suite cannot run due to dependency incompatabilities.
`#321 <https://github.com/python-attrs/attrs/issues/321>`_,
`#334 <https://github.com/python-attrs/attrs/issues/334>`_
- If ``attr.s`` is passed a *these* argument, it will not attempt to remove attributes with the same name from the class body anymore.
`#322 <https://github.com/python-attrs/attrs/issues/322>`_,
`#323 <https://github.com/python-attrs/attrs/issues/323>`_
- The hash of ``attr.NOTHING`` is now vegan and faster on 32bit Python builds.
`#331 <https://github.com/python-attrs/attrs/issues/331>`_,
`#332 <https://github.com/python-attrs/attrs/issues/332>`_
- The overhead of instantiating frozen dict classes is virtually eliminated.
`#336 <https://github.com/python-attrs/attrs/issues/336>`_
- Generated ``__init__`` methods now have an ``__annotations__`` attribute derived from the types of the fields.
`#363 <https://github.com/python-attrs/attrs/issues/363>`_
- We have restructured the documentation a bit to account for ``attrs``' growth in scope.
Instead of putting everything into the `examples <http://www.attrs.org/en/stable/examples.html>`_ page, we have started to extract narrative chapters.
So far, we've added chapters on `initialization <http://www.attrs.org/en/stable/init.html>`_ and `hashing <http://www.attrs.org/en/stable/hashing.html>`_.
Expect more to come!
`#369 <https://github.com/python-attrs/attrs/issues/369>`_,
`#370 <https://github.com/python-attrs/attrs/issues/370>`_
----
17.4.0 (2017-12-30)
-------------------
Backward-incompatible Changes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- The traversal of MROs when using multiple inheritance was backward:
If you defined a class ``C`` that subclasses ``A`` and ``B`` like ``C(A, B)``, ``attrs`` would have collected the attributes from ``B`` *before* those of ``A``.
This is now fixed and means that in classes that employ multiple inheritance, the output of ``__repr__`` and the order of positional arguments in ``__init__`` changes.
Due to the nature of this bug, a proper deprecation cycle was unfortunately impossible.
Generally speaking, it's advisable to prefer ``kwargs``-based initialization anyways *especially* if you employ multiple inheritance and diamond-shaped hierarchies.
`#298 <https://github.com/python-attrs/attrs/issues/298>`_,
`#299 <https://github.com/python-attrs/attrs/issues/299>`_,
`#304 <https://github.com/python-attrs/attrs/issues/304>`_
- The ``__repr__`` set by ``attrs``
no longer produces an ``AttributeError``
when the instance is missing some of the specified attributes
(either through deleting
or after using ``init=False`` on some attributes).
This can break code
that relied on ``repr(attr_cls_instance)`` raising ``AttributeError``
to check if any attr-specified members were unset.
If you were using this,
you can implement a custom method for checking this::
def has_unset_members(self):
for field in attr.fields(type(self)):
try:
getattr(self, field.name)
except AttributeError:
return True
return False
`#308 <https://github.com/python-attrs/attrs/issues/308>`_
Deprecations
^^^^^^^^^^^^
- The ``attr.ib(convert=callable)`` option is now deprecated in favor of ``attr.ib(converter=callable)``.
This is done to achieve consistency with other noun-based arguments like *validator*.
*convert* will keep working until at least January 2019 while raising a ``DeprecationWarning``.
`#307 <https://github.com/python-attrs/attrs/issues/307>`_
Changes
^^^^^^^
- Generated ``__hash__`` methods now hash the class type along with the attribute values.
Until now the hashes of two classes with the same values were identical which was a bug.
The generated method is also *much* faster now.
`#261 <https://github.com/python-attrs/attrs/issues/261>`_,
`#295 <https://github.com/python-attrs/attrs/issues/295>`_,
`#296 <https://github.com/python-attrs/attrs/issues/296>`_
- ``attr.ib``\ s ``metadata`` argument now defaults to a unique empty ``dict`` instance instead of sharing a common empty ``dict`` for all.
The singleton empty ``dict`` is still enforced.
`#280 <https://github.com/python-attrs/attrs/issues/280>`_
- ``ctypes`` is optional now however if it's missing, a bare ``super()`` will not work in slotted classes.
This should only happen in special environments like Google App Engine.
`#284 <https://github.com/python-attrs/attrs/issues/284>`_,
`#286 <https://github.com/python-attrs/attrs/issues/286>`_
- The attribute redefinition feature introduced in 17.3.0 now takes into account if an attribute is redefined via multiple inheritance.
In that case, the definition that is closer to the base of the class hierarchy wins.
`#285 <https://github.com/python-attrs/attrs/issues/285>`_,
`#287 <https://github.com/python-attrs/attrs/issues/287>`_
- Subclasses of ``auto_attribs=True`` can be empty now.
`#291 <https://github.com/python-attrs/attrs/issues/291>`_,
`#292 <https://github.com/python-attrs/attrs/issues/292>`_
- Equality tests are *much* faster now.
`#306 <https://github.com/python-attrs/attrs/issues/306>`_
- All generated methods now have correct ``__module__``, ``__name__``, and (on Python 3) ``__qualname__`` attributes.
`#309 <https://github.com/python-attrs/attrs/issues/309>`_
----
17.3.0 (2017-11-08)
-------------------
Backward-incompatible Changes
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Attributes are not defined on the class body anymore.
This means that if you define a class ``C`` with an attribute ``x``, the class will *not* have an attribute ``x`` for introspection anymore.
Instead of ``C.x``, use ``attr.fields(C).x`` or look at ``C.__attrs_attrs__``.
The old behavior has been deprecated since version 16.1.
(`#253 <https://github.com/python-attrs/attrs/issues/253>`_)
Changes
^^^^^^^
- ``super()`` and ``__class__`` now work with slotted classes on Python 3.
(`#102 <https://github.com/python-attrs/attrs/issues/102>`_, `#226 <https://github.com/python-attrs/attrs/issues/226>`_, `#269 <https://github.com/python-attrs/attrs/issues/269>`_, `#270 <https://github.com/python-attrs/attrs/issues/270>`_, `#272 <https://github.com/python-attrs/attrs/issues/272>`_)
- Added ``type`` argument to ``attr.ib()`` and corresponding ``type`` attribute to ``attr.Attribute``.
This change paves the way for automatic type checking and serialization (though as of this release ``attrs`` does not make use of it).
In Python 3.6 or higher, the value of ``attr.Attribute.type`` can alternately be set using variable type annotations
(see `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_). (`#151 <https://github.com/python-attrs/attrs/issues/151>`_, `#214 <https://github.com/python-attrs/attrs/issues/214>`_, `#215 <https://github.com/python-attrs/attrs/issues/215>`_, `#239 <https://github.com/python-attrs/attrs/issues/239>`_)
- The combination of ``str=True`` and ``slots=True`` now works on Python 2.
(`#198 <https://github.com/python-attrs/attrs/issues/198>`_)
- ``attr.Factory`` is hashable again. (`#204
<https://github.com/python-attrs/attrs/issues/204>`_)
- Subclasses now can overwrite attribute definitions of their superclass.
That means that you can -- for example -- change the default value for an attribute by redefining it.
(`#221 <https://github.com/python-attrs/attrs/issues/221>`_, `#229 <https://github.com/python-attrs/attrs/issues/229>`_)
- Added new option ``auto_attribs`` to ``@attr.s`` that allows to collect annotated fields without setting them to ``attr.ib()``.
Setting a field to an ``attr.ib()`` is still possible to supply options like validators.
Setting it to any other value is treated like it was passed as ``attr.ib(default=value)`` -- passing an instance of ``attr.Factory`` also works as expected.
(`#262 <https://github.com/python-attrs/attrs/issues/262>`_, `#277 <https://github.com/python-attrs/attrs/issues/277>`_)
- Instances of classes created using ``attr.make_class()`` can now be pickled.
(`#282 <https://github.com/python-attrs/attrs/issues/282>`_)
----
17.2.0 (2017-05-24)
-------------------
Changes:
^^^^^^^^
- Validators are hashable again.
Note that validators may become frozen in the future, pending availability of no-overhead frozen classes.
`#192 <https://github.com/python-attrs/attrs/issues/192>`_
----
17.1.0 (2017-05-16)
-------------------
To encourage more participation, the project has also been moved into a `dedicated GitHub organization <https://github.com/python-attrs/>`_ and everyone is most welcome to join!
``attrs`` also has a logo now!
.. image:: http://www.attrs.org/en/latest/_static/attrs_logo.png
:alt: attrs logo
Backward-incompatible Changes:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- ``attrs`` will set the ``__hash__()`` method to ``None`` by default now.
The way hashes were handled before was in conflict with `Python's specification <https://docs.python.org/3/reference/datamodel.html#object.__hash__>`_.
This *may* break some software although this breakage is most likely just surfacing of latent bugs.
You can always make ``attrs`` create the ``__hash__()`` method using ``@attr.s(hash=True)``.
See `#136`_ for the rationale of this change.
.. warning::
Please *do not* upgrade blindly and *do* test your software!
*Especially* if you use instances as dict keys or put them into sets!
- Correspondingly, ``attr.ib``'s ``hash`` argument is ``None`` by default too and mirrors the ``cmp`` argument as it should.
Deprecations:
^^^^^^^^^^^^^
- ``attr.assoc()`` is now deprecated in favor of ``attr.evolve()`` and will stop working in 2018.
Changes:
^^^^^^^^
- Fix default hashing behavior.
Now *hash* mirrors the value of *cmp* and classes are unhashable by default.
`#136`_
`#142 <https://github.com/python-attrs/attrs/issues/142>`_
- Added ``attr.evolve()`` that, given an instance of an ``attrs`` class and field changes as keyword arguments, will instantiate a copy of the given instance with the changes applied.
``evolve()`` replaces ``assoc()``, which is now deprecated.
``evolve()`` is significantly faster than ``assoc()``, and requires the class have an initializer that can take the field values as keyword arguments (like ``attrs`` itself can generate).
`#116 <https://github.com/python-attrs/attrs/issues/116>`_
`#124 <https://github.com/python-attrs/attrs/pull/124>`_
`#135 <https://github.com/python-attrs/attrs/pull/135>`_
- ``FrozenInstanceError`` is now raised when trying to delete an attribute from a frozen class.
`#118 <https://github.com/python-attrs/attrs/pull/118>`_
- Frozen-ness of classes is now inherited.
`#128 <https://github.com/python-attrs/attrs/pull/128>`_
- ``__attrs_post_init__()`` is now run if validation is disabled.
`#130 <https://github.com/python-attrs/attrs/pull/130>`_
- Added ``attr.validators.in_(options)`` that, given the allowed `options`, checks whether the attribute value is in it.
This can be used to check constants, enums, mappings, etc.
`#181 <https://github.com/python-attrs/attrs/pull/181>`_
- Added ``attr.validators.and_()`` that composes multiple validators into one.
`#161 <https://github.com/python-attrs/attrs/issues/161>`_
- For convenience, the ``validator`` argument of ``@attr.s`` now can take a ``list`` of validators that are wrapped using ``and_()``.
`#138 <https://github.com/python-attrs/attrs/issues/138>`_
- Accordingly, ``attr.validators.optional()`` now can take a ``list`` of validators too.
`#161 <https://github.com/python-attrs/attrs/issues/161>`_
- Validators can now be defined conveniently inline by using the attribute as a decorator.
Check out the `examples <http://www.attrs.org/en/stable/examples.html#validators>`_ to see it in action!
`#143 <https://github.com/python-attrs/attrs/issues/143>`_
- ``attr.Factory()`` now has a ``takes_self`` argument that makes the initializer to pass the partially initialized instance into the factory.
In other words you can define attribute defaults based on other attributes.
`#165`_
`#189 <https://github.com/python-attrs/attrs/issues/189>`_
- Default factories can now also be defined inline using decorators.
They are *always* passed the partially initialized instance.
`#165`_
- Conversion can now be made optional using ``attr.converters.optional()``.
`#105 <https://github.com/python-attrs/attrs/issues/105>`_
`#173 <https://github.com/python-attrs/attrs/pull/173>`_
- ``attr.make_class()`` now accepts the keyword argument ``bases`` which allows for subclassing.
`#152 <https://github.com/python-attrs/attrs/pull/152>`_
- Metaclasses are now preserved with ``slots=True``.
`#155 <https://github.com/python-attrs/attrs/pull/155>`_
.. _`#136`: https://github.com/python-attrs/attrs/issues/136
.. _`#165`: https://github.com/python-attrs/attrs/issues/165
----
16.3.0 (2016-11-24)
-------------------
Changes:
^^^^^^^^
- Attributes now can have user-defined metadata which greatly improves ``attrs``'s extensibility.
`#96 <https://github.com/python-attrs/attrs/pull/96>`_
- Allow for a ``__attrs_post_init__()`` method that -- if defined -- will get called at the end of the ``attrs``-generated ``__init__()`` method.
`#111 <https://github.com/python-attrs/attrs/pull/111>`_
- Added ``@attr.s(str=True)`` that will optionally create a ``__str__()`` method that is identical to ``__repr__()``.
This is mainly useful with ``Exception``\ s and other classes that rely on a useful ``__str__()`` implementation but overwrite the default one through a poor own one.
Default Python class behavior is to use ``__repr__()`` as ``__str__()`` anyways.
If you tried using ``attrs`` with ``Exception``\ s and were puzzled by the tracebacks: this option is for you.
- ``__name__`` is not overwritten with ``__qualname__`` for ``attr.s(slots=True)`` classes anymore.
`#99 <https://github.com/python-attrs/attrs/issues/99>`_
----
16.2.0 (2016-09-17)
-------------------
Changes:
^^^^^^^^
- Added ``attr.astuple()`` that -- similarly to ``attr.asdict()`` -- returns the instance as a tuple.
`#77 <https://github.com/python-attrs/attrs/issues/77>`_
- Converts now work with frozen classes.
`#76 <https://github.com/python-attrs/attrs/issues/76>`_
- Instantiation of ``attrs`` classes with converters is now significantly faster.
`#80 <https://github.com/python-attrs/attrs/pull/80>`_
- Pickling now works with slotted classes.
`#81 <https://github.com/python-attrs/attrs/issues/81>`_
- ``attr.assoc()`` now works with slotted classes.
`#84 <https://github.com/python-attrs/attrs/issues/84>`_
- The tuple returned by ``attr.fields()`` now also allows to access the ``Attribute`` instances by name.
Yes, we've subclassed ``tuple`` so you don't have to!
Therefore ``attr.fields(C).x`` is equivalent to the deprecated ``C.x`` and works with slotted classes.
`#88 <https://github.com/python-attrs/attrs/issues/88>`_
----
16.1.0 (2016-08-30)
-------------------
Backward-incompatible Changes:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- All instances where function arguments were called ``cl`` have been changed to the more Pythonic ``cls``.
Since it was always the first argument, it's doubtful anyone ever called those function with in the keyword form.
If so, sorry for any breakage but there's no practical deprecation path to solve this ugly wart.
Deprecations:
^^^^^^^^^^^^^
- Accessing ``Attribute`` instances on class objects is now deprecated and will stop working in 2017.
If you need introspection please use the ``__attrs_attrs__`` attribute or the ``attr.fields()`` function that carry them too.
In the future, the attributes that are defined on the class body and are usually overwritten in your ``__init__`` method are simply removed after ``@attr.s`` has been applied.
This will remove the confusing error message if you write your own ``__init__`` and forget to initialize some attribute.
Instead you will get a straightforward ``AttributeError``.
In other words: decorated classes will work more like plain Python classes which was always ``attrs``'s goal.
- The serious business aliases ``attr.attributes`` and ``attr.attr`` have been deprecated in favor of ``attr.attrs`` and ``attr.attrib`` which are much more consistent and frankly obvious in hindsight.
They will be purged from documentation immediately but there are no plans to actually remove them.
Changes:
^^^^^^^^
- ``attr.asdict()``\ 's ``dict_factory`` arguments is now propagated on recursion.
`#45 <https://github.com/python-attrs/attrs/issues/45>`_
- ``attr.asdict()``, ``attr.has()`` and ``attr.fields()`` are significantly faster.
`#48 <https://github.com/python-attrs/attrs/issues/48>`_
`#51 <https://github.com/python-attrs/attrs/issues/51>`_
- Add ``attr.attrs`` and ``attr.attrib`` as a more consistent aliases for ``attr.s`` and ``attr.ib``.
- Add ``frozen`` option to ``attr.s`` that will make instances best-effort immutable.
`#60 <https://github.com/python-attrs/attrs/issues/60>`_
- ``attr.asdict()`` now takes ``retain_collection_types`` as an argument.
If ``True``, it does not convert attributes of type ``tuple`` or ``set`` to ``list``.
`#69 <https://github.com/python-attrs/attrs/issues/69>`_
----
16.0.0 (2016-05-23)
-------------------
Backward-incompatible Changes:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Python 3.3 and 2.6 aren't supported anymore.
They may work by chance but any effort to keep them working has ceased.
The last Python 2.6 release was on October 29, 2013 and isn't supported by the CPython core team anymore.
Major Python packages like Django and Twisted dropped Python 2.6 a while ago already.
Python 3.3 never had a significant user base and wasn't part of any distribution's LTS release.
Changes:
^^^^^^^^
- ``__slots__`` have arrived!
Classes now can automatically be `slotted <https://docs.python.org/3/reference/datamodel.html#slots>`_-style (and save your precious memory) just by passing ``slots=True``.
`#35 <https://github.com/python-attrs/attrs/issues/35>`_
- Allow the case of initializing attributes that are set to ``init=False``.
This allows for clean initializer parameter lists while being able to initialize attributes to default values.
`#32 <https://github.com/python-attrs/attrs/issues/32>`_
- ``attr.asdict()`` can now produce arbitrary mappings instead of Python ``dict``\ s when provided with a ``dict_factory`` argument.
`#40 <https://github.com/python-attrs/attrs/issues/40>`_
- Multiple performance improvements.
----
15.2.0 (2015-12-08)
-------------------
Changes:
^^^^^^^^
- Added 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 <https://github.com/python-attrs/attrs/issues/26>`_
- Speed up object creation when attribute validators are used.
`#28 <https://github.com/python-attrs/attrs/issues/28>`_
----
15.1.0 (2015-08-20)
-------------------
Changes:
^^^^^^^^
- Added ``attr.validators.optional()`` that wraps other validators allowing attributes to be ``None``.
`#16 <https://github.com/python-attrs/attrs/issues/16>`_
- Multi-level inheritance now works.
`#24 <https://github.com/python-attrs/attrs/issues/24>`_
- ``__repr__()`` now works with non-redecorated subclasses.
`#20 <https://github.com/python-attrs/attrs/issues/20>`_
----
15.0.0 (2015-04-15)
-------------------
Changes:
^^^^^^^^
Initial release.

21
third_party/python/attrs/LICENSE vendored Normal file
View File

@ -0,0 +1,21 @@
The 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.

22
third_party/python/attrs/MANIFEST.in vendored Normal file
View File

@ -0,0 +1,22 @@
include LICENSE *.rst *.toml .readthedocs.yml
# Don't package GitHub-specific files.
exclude .github/*.md .travis.yml
# Tests
include tox.ini .coveragerc conftest.py
recursive-include tests *.py
recursive-include .github *.rst
# Documentation
include docs/Makefile docs/docutils.conf
recursive-include docs *.png
recursive-include docs *.svg
recursive-include docs *.py
recursive-include docs *.rst
prune docs/_build
# Just to keep check-manifest happy; on releases those files are gone.
# Last rule wins!
exclude changelog.d/*.rst
include changelog.d/towncrier_template.rst

240
third_party/python/attrs/PKG-INFO vendored Normal file
View File

@ -0,0 +1,240 @@
Metadata-Version: 2.1
Name: attrs
Version: 18.1.0
Summary: Classes Without Boilerplate
Home-page: http://www.attrs.org/
Author: Hynek Schlawack
Author-email: hs@ox.cx
Maintainer: Hynek Schlawack
Maintainer-email: hs@ox.cx
License: MIT
Description: .. image:: http://www.attrs.org/en/latest/_static/attrs_logo.png
:alt: attrs Logo
======================================
``attrs``: Classes Without Boilerplate
======================================
.. image:: https://readthedocs.org/projects/attrs/badge/?version=stable
:target: http://www.attrs.org/en/stable/?badge=stable
:alt: Documentation Status
.. image:: https://travis-ci.org/python-attrs/attrs.svg?branch=master
:target: https://travis-ci.org/python-attrs/attrs
:alt: CI Status
.. image:: https://codecov.io/github/python-attrs/attrs/branch/master/graph/badge.svg
:target: https://codecov.io/github/python-attrs/attrs
:alt: Test Coverage
.. teaser-begin
``attrs`` is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka `dunder <https://nedbatchelder.com/blog/200605/dunder.html>`_ methods).
Its main goal is to help you to write **concise** and **correct** software without slowing down your code.
.. -spiel-end-
For that, it gives you a class decorator and a way to declaratively define the attributes on that class:
.. -code-begin-
.. code-block:: pycon
>>> import attr
>>> @attr.s
... class SomeClass(object):
... a_number = attr.ib(default=42)
... list_of_numbers = attr.ib(default=attr.Factory(list))
...
... def hard_math(self, another_number):
... return self.a_number + sum(self.list_of_numbers) * another_number
>>> sc = SomeClass(1, [1, 2, 3])
>>> sc
SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
>>> sc.hard_math(3)
19
>>> sc == SomeClass(1, [1, 2, 3])
True
>>> sc != SomeClass(2, [3, 2, 1])
True
>>> attr.asdict(sc)
{'a_number': 1, 'list_of_numbers': [1, 2, 3]}
>>> SomeClass()
SomeClass(a_number=42, list_of_numbers=[])
>>> C = attr.make_class("C", ["a", "b"])
>>> C("foo", "bar")
C(a='foo', b='bar')
After *declaring* your attributes ``attrs`` gives you:
- a concise and explicit overview of the class's attributes,
- a nice human-readable ``__repr__``,
- a complete set of comparison methods,
- an initializer,
- and much more,
*without* writing dull boilerplate code again and again and *without* runtime performance penalties.
This gives you the power to use actual classes with actual types in your code instead of confusing ``tuple``\ s or `confusingly behaving <http://www.attrs.org/en/stable/why.html#namedtuples>`_ ``namedtuple``\ s.
Which in turn encourages you to write *small classes* that do `one thing well <https://www.destroyallsoftware.com/talks/boundaries>`_.
Never again violate the `single responsibility principle <https://en.wikipedia.org/wiki/Single_responsibility_principle>`_ just because implementing ``__init__`` et al is a painful drag.
.. -testimonials-
Testimonials
============
**Amber Hawkie Brown**, Twisted Release Manager and Computer Owl:
Writing a fully-functional class using attrs takes me less time than writing this testimonial.
**Glyph Lefkowitz**, creator of `Twisted <https://twistedmatrix.com/>`_, `Automat <https://pypi.python.org/pypi/Automat>`_, and other open source software, in `The One Python Library Everyone Needs <https://glyph.twistedmatrix.com/2016/08/attrs.html>`_:
Im looking forward to is being able to program in Python-with-attrs everywhere.
It exerts a subtle, but positive, design influence in all the codebases Ive see it used in.
**Kenneth Reitz**, author of `requests <http://www.python-requests.org/>`_, Python Overlord at Heroku, `on paper no less <https://twitter.com/hynek/status/866817877650751488>`_:
attrs—classes for humans. I like it.
**Łukasz Langa**, prolific CPython core developer and Production Engineer at Facebook:
I'm increasingly digging your attr.ocity. Good job!
.. -end-
.. -project-information-
Getting Help
============
Please use the ``python-attrs`` tag on `StackOverflow <https://stackoverflow.com/questions/tagged/python-attrs>`_ to get help.
Answering questions of your fellow developers is also great way to help the project!
Project Information
===================
``attrs`` is released under the `MIT <https://choosealicense.com/licenses/mit/>`_ license,
its documentation lives at `Read the Docs <http://www.attrs.org/>`_,
the code on `GitHub <https://github.com/python-attrs/attrs>`_,
and the latest release on `PyPI <https://pypi.org/project/attrs/>`_.
Its rigorously tested on Python 2.7, 3.4+, and PyPy.
We collect information on **third-party extensions** in our `wiki <https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs>`_.
Feel free to browse and add your own!
If you'd like to contribute to ``attrs`` you're most welcome and we've written `a little guide <http://www.attrs.org/en/latest/contributing.html>`_ to get you started!
Release Information
===================
18.1.0 (2018-05-03)
-------------------
Changes
^^^^^^^
- ``x=X(); x.cycle = x; repr(x)`` will no longer raise a ``RecursionError``, and will instead show as ``X(x=...)``.
`#95 <https://github.com/python-attrs/attrs/issues/95>`_
- ``attr.ib(factory=f)`` is now syntactic sugar for the common case of ``attr.ib(default=attr.Factory(f))``.
`#178 <https://github.com/python-attrs/attrs/issues/178>`_,
`#356 <https://github.com/python-attrs/attrs/issues/356>`_
- Added ``attr.field_dict()`` to return an ordered dictionary of ``attrs`` attributes for a class, whose keys are the attribute names.
`#290 <https://github.com/python-attrs/attrs/issues/290>`_,
`#349 <https://github.com/python-attrs/attrs/issues/349>`_
- The order of attributes that are passed into ``attr.make_class()`` or the ``these`` argument of ``@attr.s()`` is now retained if the dictionary is ordered (i.e. ``dict`` on Python 3.6 and later, ``collections.OrderedDict`` otherwise).
Before, the order was always determined by the order in which the attributes have been defined which may not be desirable when creating classes programatically.
`#300 <https://github.com/python-attrs/attrs/issues/300>`_,
`#339 <https://github.com/python-attrs/attrs/issues/339>`_,
`#343 <https://github.com/python-attrs/attrs/issues/343>`_
- In slotted classes, ``__getstate__`` and ``__setstate__`` now ignore the ``__weakref__`` attribute.
`#311 <https://github.com/python-attrs/attrs/issues/311>`_,
`#326 <https://github.com/python-attrs/attrs/issues/326>`_
- Setting the cell type is now completely best effort.
This fixes ``attrs`` on Jython.
We cannot make any guarantees regarding Jython though, because our test suite cannot run due to dependency incompatabilities.
`#321 <https://github.com/python-attrs/attrs/issues/321>`_,
`#334 <https://github.com/python-attrs/attrs/issues/334>`_
- If ``attr.s`` is passed a *these* argument, it will not attempt to remove attributes with the same name from the class body anymore.
`#322 <https://github.com/python-attrs/attrs/issues/322>`_,
`#323 <https://github.com/python-attrs/attrs/issues/323>`_
- The hash of ``attr.NOTHING`` is now vegan and faster on 32bit Python builds.
`#331 <https://github.com/python-attrs/attrs/issues/331>`_,
`#332 <https://github.com/python-attrs/attrs/issues/332>`_
- The overhead of instantiating frozen dict classes is virtually eliminated.
`#336 <https://github.com/python-attrs/attrs/issues/336>`_
- Generated ``__init__`` methods now have an ``__annotations__`` attribute derived from the types of the fields.
`#363 <https://github.com/python-attrs/attrs/issues/363>`_
- We have restructured the documentation a bit to account for ``attrs``' growth in scope.
Instead of putting everything into the `examples <http://www.attrs.org/en/stable/examples.html>`_ page, we have started to extract narrative chapters.
So far, we've added chapters on `initialization <http://www.attrs.org/en/stable/init.html>`_ and `hashing <http://www.attrs.org/en/stable/hashing.html>`_.
Expect more to come!
`#369 <https://github.com/python-attrs/attrs/issues/369>`_,
`#370 <https://github.com/python-attrs/attrs/issues/370>`_
`Full changelog <http://www.attrs.org/en/stable/changelog.html>`_.
Credits
=======
``attrs`` is written and maintained by `Hynek Schlawack <https://hynek.me/>`_.
The development is kindly supported by `Variomedia AG <https://www.variomedia.de/>`_.
A full list of contributors can be found in `GitHub's overview <https://github.com/python-attrs/attrs/graphs/contributors>`_.
Its the spiritual successor of `characteristic <https://characteristic.readthedocs.io/>`_ and aspires to fix some of it clunkiness and unfortunate decisions.
Both were inspired by Twisteds `FancyEqMixin <https://twistedmatrix.com/documents/current/api/twisted.python.util.FancyEqMixin.html>`_ but both are implemented using class decorators because `sub-classing is bad for you <https://www.youtube.com/watch?v=3MNVP9-hglc>`_, mkay?
Keywords: class,attribute,boilerplate
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Natural Language :: English
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Provides-Extra: tests
Provides-Extra: docs
Provides-Extra: dev

132
third_party/python/attrs/README.rst vendored Normal file
View File

@ -0,0 +1,132 @@
.. image:: http://www.attrs.org/en/latest/_static/attrs_logo.png
:alt: attrs Logo
======================================
``attrs``: Classes Without Boilerplate
======================================
.. image:: https://readthedocs.org/projects/attrs/badge/?version=stable
:target: http://www.attrs.org/en/stable/?badge=stable
:alt: Documentation Status
.. image:: https://travis-ci.org/python-attrs/attrs.svg?branch=master
:target: https://travis-ci.org/python-attrs/attrs
:alt: CI Status
.. image:: https://codecov.io/github/python-attrs/attrs/branch/master/graph/badge.svg
:target: https://codecov.io/github/python-attrs/attrs
:alt: Test Coverage
.. teaser-begin
``attrs`` is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka `dunder <https://nedbatchelder.com/blog/200605/dunder.html>`_ methods).
Its main goal is to help you to write **concise** and **correct** software without slowing down your code.
.. -spiel-end-
For that, it gives you a class decorator and a way to declaratively define the attributes on that class:
.. -code-begin-
.. code-block:: pycon
>>> import attr
>>> @attr.s
... class SomeClass(object):
... a_number = attr.ib(default=42)
... list_of_numbers = attr.ib(default=attr.Factory(list))
...
... def hard_math(self, another_number):
... return self.a_number + sum(self.list_of_numbers) * another_number
>>> sc = SomeClass(1, [1, 2, 3])
>>> sc
SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
>>> sc.hard_math(3)
19
>>> sc == SomeClass(1, [1, 2, 3])
True
>>> sc != SomeClass(2, [3, 2, 1])
True
>>> attr.asdict(sc)
{'a_number': 1, 'list_of_numbers': [1, 2, 3]}
>>> SomeClass()
SomeClass(a_number=42, list_of_numbers=[])
>>> C = attr.make_class("C", ["a", "b"])
>>> C("foo", "bar")
C(a='foo', b='bar')
After *declaring* your attributes ``attrs`` gives you:
- a concise and explicit overview of the class's attributes,
- a nice human-readable ``__repr__``,
- a complete set of comparison methods,
- an initializer,
- and much more,
*without* writing dull boilerplate code again and again and *without* runtime performance penalties.
This gives you the power to use actual classes with actual types in your code instead of confusing ``tuple``\ s or `confusingly behaving <http://www.attrs.org/en/stable/why.html#namedtuples>`_ ``namedtuple``\ s.
Which in turn encourages you to write *small classes* that do `one thing well <https://www.destroyallsoftware.com/talks/boundaries>`_.
Never again violate the `single responsibility principle <https://en.wikipedia.org/wiki/Single_responsibility_principle>`_ just because implementing ``__init__`` et al is a painful drag.
.. -testimonials-
Testimonials
============
**Amber Hawkie Brown**, Twisted Release Manager and Computer Owl:
Writing a fully-functional class using attrs takes me less time than writing this testimonial.
**Glyph Lefkowitz**, creator of `Twisted <https://twistedmatrix.com/>`_, `Automat <https://pypi.python.org/pypi/Automat>`_, and other open source software, in `The One Python Library Everyone Needs <https://glyph.twistedmatrix.com/2016/08/attrs.html>`_:
Im looking forward to is being able to program in Python-with-attrs everywhere.
It exerts a subtle, but positive, design influence in all the codebases Ive see it used in.
**Kenneth Reitz**, author of `requests <http://www.python-requests.org/>`_, Python Overlord at Heroku, `on paper no less <https://twitter.com/hynek/status/866817877650751488>`_:
attrs—classes for humans. I like it.
**Łukasz Langa**, prolific CPython core developer and Production Engineer at Facebook:
I'm increasingly digging your attr.ocity. Good job!
.. -end-
.. -project-information-
Getting Help
============
Please use the ``python-attrs`` tag on `StackOverflow <https://stackoverflow.com/questions/tagged/python-attrs>`_ to get help.
Answering questions of your fellow developers is also great way to help the project!
Project Information
===================
``attrs`` is released under the `MIT <https://choosealicense.com/licenses/mit/>`_ license,
its documentation lives at `Read the Docs <http://www.attrs.org/>`_,
the code on `GitHub <https://github.com/python-attrs/attrs>`_,
and the latest release on `PyPI <https://pypi.org/project/attrs/>`_.
Its rigorously tested on Python 2.7, 3.4+, and PyPy.
We collect information on **third-party extensions** in our `wiki <https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs>`_.
Feel free to browse and add your own!
If you'd like to contribute to ``attrs`` you're most welcome and we've written `a little guide <http://www.attrs.org/en/latest/contributing.html>`_ to get you started!

View File

@ -0,0 +1,35 @@
{% for section, _ in sections.items() %}
{% set underline = underlines[0] %}{% if section %}{{section}}
{{ underline * section|length }}{% set underline = underlines[1] %}
{% endif %}
{% if sections[section] %}
{% for category, val in definitions.items() if category in sections[section]%}
{{ definitions[category]['name'] }}
{{ underline * definitions[category]['name']|length }}
{% if definitions[category]['showcontent'] %}
{% for text, values in sections[section][category].items() %}
- {{ text }}
{{ values|join(',\n ') }}
{% endfor %}
{% else %}
- {{ sections[section][category]['']|join(', ') }}
{% endif %}
{% if sections[section][category]|length == 0 %}
No significant changes.
{% else %}
{% endif %}
{% endfor %}
{% else %}
No significant changes.
{% endif %}
{% endfor %}
----

28
third_party/python/attrs/conftest.py vendored Normal file
View File

@ -0,0 +1,28 @@
from __future__ import absolute_import, division, print_function
import sys
import pytest
@pytest.fixture(scope="session")
def C():
"""
Return a simple but fully featured attrs class with an x and a y attribute.
"""
import attr
@attr.s
class C(object):
x = attr.ib()
y = attr.ib()
return C
collect_ignore = []
if sys.version_info[:2] < (3, 6):
collect_ignore.extend([
"tests/test_annotations.py",
"tests/test_init_subclass.py",
])

177
third_party/python/attrs/docs/Makefile vendored Normal file
View File

@ -0,0 +1,177 @@
# 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 <target>' where <target> 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."

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 6.6 KiB

396
third_party/python/attrs/docs/api.rst vendored Normal file
View File

@ -0,0 +1,396 @@
.. _api:
API Reference
=============
.. 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=None, init=True, slots=False, frozen=False, str=False, auto_attribs=False)
.. note::
``attrs`` also comes with a serious business alias ``attr.attrs``.
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 object at ...>
>>> D = attr.s(these={"x": attr.ib()}, init=False)(D)
>>> D(1)
D(x=1)
.. autofunction:: attr.ib
.. note::
``attrs`` also comes with a serious business alias ``attr.attrib``.
The object returned by :func:`attr.ib` also allows for setting the default and the validator using decorators:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib()
... @x.validator
... def name_can_be_anything(self, attribute, value):
... if value < 0:
... raise ValueError("x must be positive")
... @y.default
... def name_does_not_matter(self):
... return self.x + 1
>>> C(1)
C(x=1, y=2)
>>> C(-1)
Traceback (most recent call last):
...
ValueError: x must be positive
.. autoclass:: attr.Attribute
Instances of this class are frequently used for introspection purposes like:
- :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()
>>> attr.fields(C).x
Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=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))
... y = attr.ib(default=attr.Factory(
... lambda self: set(self.x),
... takes_self=True)
... )
>>> C()
C(x=[], y=set())
>>> C([1, 2, 3])
C(x=[1, 2, 3], y={1, 2, 3})
.. autoexception:: attr.exceptions.FrozenInstanceError
.. autoexception:: attr.exceptions.AttrsAttributeNotFoundError
.. autoexception:: attr.exceptions.NotAnAttrsClassError
.. autoexception:: attr.exceptions.DefaultAlreadySetError
.. autoexception:: attr.exceptions.UnannotatedAttributeError
For example::
@attr.s(auto_attribs=True)
class C:
x: int
y = attr.ib() # <- ERROR!
.. _helpers:
Helpers
-------
``attrs`` comes with a bunch of helper methods that make working 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=None, init=True, metadata=mappingproxy({}), type=None, converter=None), Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None))
>>> attr.fields(C)[1]
Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None)
>>> attr.fields(C).y is attr.fields(C)[1]
True
.. autofunction:: attr.fields_dict
For example:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib()
>>> attr.fields_dict(C)
{'x': Attribute(name='x', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None), 'y': Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None)}
>>> attr.fields_dict(C)['y']
Attribute(name='y', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=None)
>>> attr.fields_dict(C)['y'] is attr.fields(C).y
True
.. 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)))
{'x': 1, 'y': {'x': 2, 'y': 3}}
.. autofunction:: attr.astuple
For example:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib()
>>> attr.astuple(C(1,2))
(1, 2)
``attrs`` includes some handy helpers for filtering:
.. autofunction:: attr.filters.include
.. autofunction:: attr.filters.exclude
See :ref:`asdict` for examples.
.. autofunction:: attr.evolve
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.evolve(i1, y=3)
>>> i2
C(x=1, y=3)
>>> i1 == i2
False
``evolve`` creates a new instance using ``__init__``.
This fact has several implications:
* private attributes should be specified without the leading underscore, just like in ``__init__``.
* attributes with ``init=False`` can't be set with ``evolve``.
* the usual ``__init__`` validators will validate the new values.
.. 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 <type 'int'> (got '1' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, repr=True, cmp=True, hash=None, init=True, type=None), <type 'int'>, '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 in 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 <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None), <type 'int'>, '42')
>>> C(None)
Traceback (most recent call last):
...
TypeError: ("'x' must be <type 'int'> (got None that is a <type 'NoneType'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, repr=True, cmp=True, hash=None, init=True, type=None), <type 'int'>, None)
.. autofunction:: attr.validators.in_
For example:
.. doctest::
>>> import enum
>>> class State(enum.Enum):
... ON = "on"
... OFF = "off"
>>> @attr.s
... class C(object):
... state = attr.ib(validator=attr.validators.in_(State))
... val = attr.ib(validator=attr.validators.in_([1, 2, 3]))
>>> C(State.ON, 1)
C(state=<State.ON: 'on'>, val=1)
>>> C("on", 1)
Traceback (most recent call last):
...
ValueError: 'state' must be in <enum 'State'> (got 'on')
>>> C(State.ON, 4)
Traceback (most recent call last):
...
ValueError: 'val' must be in [1, 2, 3] (got 4)
.. autofunction:: attr.validators.provides
.. autofunction:: attr.validators.and_
For convenience, it's also possible to pass a list to :func:`attr.ib`'s validator argument.
Thus the following two statements are equivalent::
x = attr.ib(validator=attr.validators.and_(v1, v2, v3))
x = attr.ib(validator=[v1, v2, v3])
.. 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 <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None), <type 'int'>, '42')
>>> C(None)
C(x=None)
Converters
----------
.. autofunction:: attr.converters.optional
For example:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(converter=attr.converters.optional(int))
>>> C(None)
C(x=None)
>>> C(42)
C(x=42)
Deprecated APIs
---------------
The serious business aliases used to be called ``attr.attributes`` and ``attr.attr``.
There are no plans to remove them but they shouldn't be used in new code.
.. autofunction:: assoc

View File

@ -0,0 +1,19 @@
Backward Compatibility
======================
.. currentmodule:: attr
``attrs`` has a very strong backward compatibility policy that is inspired by the policy of the `Twisted framework <https://twistedmatrix.com/trac/wiki/CompatibilityPolicy>`_.
Put simply, you shouldn't ever be afraid to upgrade ``attrs`` if you're only using its public APIs.
If there will ever be a need to break compatibility, it will be announced in the :doc:`changelog` and raise a ``DeprecationWarning`` for a year (if possible) before it's finally really broken.
.. _exemption:
.. warning::
The structure of the :class:`attr.Attribute` class is exempt from this rule.
It *will* change in the future, but 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.

View File

@ -0,0 +1 @@
.. include:: ../CHANGELOG.rst

155
third_party/python/attrs/docs/conf.py vendored Normal file
View File

@ -0,0 +1,155 @@
# -*- coding: utf-8 -*-
import codecs
import os
import re
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.")
# -- General configuration ------------------------------------------------
# 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 master toctree document.
master_doc = 'index'
# General information about the project.
project = u'attrs'
copyright = u'2015, Hynek Schlawack'
# 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.
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = "alabaster"
html_theme_options = {
"font_family": '"Avenir Next", Calibri, "PT Sans", sans-serif',
"head_font_family": '"Avenir Next", Calibri, "PT Sans", sans-serif',
"font_size": "18px",
"page_width": "980px",
}
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = "_static/attrs_logo.svg"
# 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']
# 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 = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
# html_use_opensearch = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'attrsdoc'
# -- 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)
]
# -- 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'),
]
intersphinx_mapping = {
"https://docs.python.org/3": None,
}
# Allow non-local URIs so we can have images in CHANGELOG etc.
suppress_warnings = ['image.nonlocal_uri']

View File

@ -0,0 +1,5 @@
.. _contributing:
.. include:: ../.github/CONTRIBUTING.rst
.. include:: ../.github/CODE_OF_CONDUCT.rst

View File

@ -0,0 +1,3 @@
[parsers]
[restructuredtext parser]
smart_quotes=yes

View File

@ -0,0 +1,601 @@
.. _examples:
``attrs`` by Example
====================
Basics
------
The simplest possible usage is:
.. doctest::
>>> import attr
>>> @attr.s
... class Empty(object):
... pass
>>> Empty()
Empty()
>>> Empty() == Empty()
True
>>> Empty() is Empty()
False
So in other words: ``attrs`` is 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()
By default, all features are added, so you immediately have 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 for both positional and keyword arguments.
If playful naming turns you off, ``attrs`` comes with serious business aliases:
.. doctest::
>>> from attr import attrs, attrib
>>> @attrs
... class SeriousCoordinates(object):
... x = attrib()
... y = attrib()
>>> 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)
If you want to initialize your private attributes yourself, you can do that too:
.. doctest::
>>> @attr.s
... class C(object):
... _x = attr.ib(init=False, default=42)
>>> C()
C(_x=42)
>>> C(23)
Traceback (most recent call last):
...
TypeError: __init__() takes exactly 1 argument (2 given)
An additional way 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)
`Subclassing is bad for you <https://www.youtube.com/watch?v=3MNVP9-hglc>`_, 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(A, B):
... 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 <https://www.python.org/download/releases/2.3/mro/>`_.
In Python 3, classes defined within other classes are `detected <https://www.python.org/dev/peps/pep-3155/>`_ 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 it overrides the implicit detection.
.. _asdict:
Converting to Collections Types
-------------------------------
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))
{'x': 1, 'y': 2}
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 <attr.filters.include>` or :func:`exclude <attr.filters.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(attr.fields(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, attr.fields(C).x))
{'x': 'foo', 'z': 3}
Other times, all you want is a tuple and ``attrs`` won't let you down:
.. doctest::
>>> import sqlite3
>>> import attr
>>> @attr.s
... class Foo:
... a = attr.ib()
... b = attr.ib()
>>> foo = Foo(2, 3)
>>> with sqlite3.connect(":memory:") as conn:
... c = conn.cursor()
... c.execute("CREATE TABLE foo (x INTEGER PRIMARY KEY ASC, y)") #doctest: +ELLIPSIS
... c.execute("INSERT INTO foo VALUES (?, ?)", attr.astuple(foo)) #doctest: +ELLIPSIS
... foo2 = Foo(*c.execute("SELECT x, y FROM foo").fetchone())
<sqlite3.Cursor object at ...>
<sqlite3.Cursor object at ...>
>>> foo == foo2
True
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(cls, db_string):
... # ... connect somehow to db_string ...
... return cls(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 <http://as.ynchrono.us/2014/12/asynchronous-object-initialization.html>`_.
Default factories can also be set using a decorator.
The method receives the partially initialized instance which enables you to base a default value on other attributes:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(default=1)
... y = attr.ib()
... @y.default
... def name_does_not_matter(self):
... return self.x + 1
>>> C()
C(x=1, y=2)
And since the case of ``attr.ib(default=attr.Factory(f))`` is so common, ``attrs`` also comes with syntactic sugar for it:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(factory=list)
>>> C()
C(x=[])
.. _examples_validators:
Validators
----------
Although your initializers should do as little as possible (ideally: just initialize your instance according to the arguments!), it can come in handy to do some kind of validation on the arguments.
``attrs`` offers two ways to define validators for each attribute and it's up to you to choose which one suites better your style and project.
You can use a decorator:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... @x.validator
... def check(self, attribute, value):
... if value > 42:
... raise ValueError("x must be smaller or equal to 42")
>>> C(42)
C(x=42)
>>> C(43)
Traceback (most recent call last):
...
ValueError: x must be smaller or equal to 42
...or a callable...
.. 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=[attr.validators.instance_of(int),
... 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'!
...or both at once:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(validator=attr.validators.instance_of(int))
... @x.validator
... def fits_byte(self, attribute, value):
... if not 0 <= value < 256:
... raise ValueError("value out of bounds")
>>> C(128)
C(x=128)
>>> C("128")
Traceback (most recent call last):
...
TypeError: ("'x' must be <class 'int'> (got '128' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_of validator for type <class 'int'>>, <function fits_byte at 0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=one), <class 'int'>, '128')
>>> C(256)
Traceback (most recent call last):
...
ValueError: value out of bounds
``attrs`` ships with a bunch of validators, make sure to :ref:`check them out <api_validators>` 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 <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None), <type 'int'>, '42')
Check out :ref:`validators` for more details.
Conversion
----------
Attributes can have a ``converter`` 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(converter=int)
>>> o = C("1")
>>> o.x
1
Check out :ref:`converters` for more details.
.. _metadata:
Metadata
--------
All ``attrs`` attributes may include arbitrary metadata in the form of a read-only dictionary.
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(metadata={'my_metadata': 1})
>>> attr.fields(C).x.metadata
mappingproxy({'my_metadata': 1})
>>> attr.fields(C).x.metadata['my_metadata']
1
Metadata is not used by ``attrs``, and is meant to enable rich functionality in third-party libraries.
The metadata dictionary follows the normal dictionary rules: keys need to be hashable, and both keys and values are recommended to be immutable.
If you're the author of a third-party library with ``attrs`` integration, please see :ref:`Extending Metadata <extending_metadata>`.
Types
-----
``attrs`` also allows you to associate a type with an attribute using either the *type* argument to :func:`attr.ib` or -- as of Python 3.6 -- using `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_-annotations:
.. doctest::
>>> @attr.s
... class C:
... x = attr.ib(type=int)
... y: int = attr.ib()
>>> attr.fields(C).x.type
<class 'int'>
>>> attr.fields(C).y.type
<class 'int'>
If you don't mind annotating *all* attributes, you can even drop the :func:`attr.ib` and assign default values instead:
.. doctest::
>>> import typing
>>> @attr.s(auto_attribs=True)
... class AutoC:
... cls_var: typing.ClassVar[int] = 5 # this one is ignored
... l: typing.List[int] = attr.Factory(list)
... x: int = 1
... foo: str = attr.ib(
... default="every attrib needs a type if auto_attribs=True"
... )
... bar: typing.Any = None
>>> attr.fields(AutoC).l.type
typing.List[int]
>>> attr.fields(AutoC).x.type
<class 'int'>
>>> attr.fields(AutoC).foo.type
<class 'str'>
>>> attr.fields(AutoC).bar.type
typing.Any
>>> AutoC()
AutoC(l=[], x=1, foo='every attrib needs a type if auto_attribs=True', bar=None)
>>> AutoC.cls_var
5
The generated ``__init__`` method will have an attribute called ``__annotations__`` that contains this type information.
.. warning::
``attrs`` itself doesn't have any features that work on top of type metadata *yet*.
However it's useful for writing your own validators or serialization frameworks.
.. _slots:
Slots
-----
:term:`Slotted classes` have a bunch of advantages on CPython.
Defining ``__slots__`` by hand is tedious, in ``attrs`` it's just a matter of passing ``slots=True``:
.. doctest::
>>> @attr.s(slots=True)
... class Coordinates(object):
... x = attr.ib()
... y = attr.ib()
Immutability
------------
Sometimes you have instances that shouldn't be changed after instantiation.
Immutability is especially popular in functional programming and is generally a very good thing.
If you'd like to enforce it, ``attrs`` will try to help:
.. doctest::
>>> @attr.s(frozen=True)
... class C(object):
... x = attr.ib()
>>> i = C(1)
>>> i.x = 2
Traceback (most recent call last):
...
attr.exceptions.FrozenInstanceError: can't set attribute
>>> i.x
1
Please note that true immutability is impossible in Python but it will :ref:`get <how-frozen>` you 99% there.
By themselves, immutable classes are useful for long-lived objects that should never change; like configurations for example.
In order to use them in regular program flow, you'll need a way to easily create new instances with changed attributes.
In Clojure that function is called `assoc <https://clojuredocs.org/clojure.core/assoc>`_ and ``attrs`` shamelessly imitates it: :func:`attr.evolve`:
.. doctest::
>>> @attr.s(frozen=True)
... class C(object):
... x = attr.ib()
... y = attr.ib()
>>> i1 = C(1, 2)
>>> i1
C(x=1, y=2)
>>> i2 = attr.evolve(i1, y=3)
>>> i2
C(x=1, y=3)
>>> i1 == i2
False
Other Goodies
-------------
Sometimes you may want to create a class programmatically.
``attrs`` won't let you down and gives you :func:`attr.make_class` :
.. 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!
<__main__.C object at ...>
>>> i.x
42
>>> i.y
[]
If you need to dynamically make a class with :func:`attr.make_class` and it needs to be a subclass of something else than ``object``, use the ``bases`` argument:
.. doctest::
>>> class D(object):
... def __eq__(self, other):
... return True # arbitrary example
>>> C = attr.make_class("C", {}, bases=(D,), cmp=False)
>>> isinstance(C(), D)
True
Sometimes, you want to have your class's ``__init__`` method do more than just
the initialization, validation, etc. that gets done for you automatically when
using ``@attr.s``.
To do this, just define a ``__attrs_post_init__`` method in your class.
It will get called at the end of the generated ``__init__`` method.
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib()
... z = attr.ib(init=False)
...
... def __attrs_post_init__(self):
... self.z = self.x + self.y
>>> obj = C(x=1, y=2)
>>> obj
C(x=1, y=2, z=3)
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')

View File

@ -0,0 +1,112 @@
.. _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(cls):
... print(cls.__attrs_attrs__)
>>> @print_attrs
... @attr.s
... class C(object):
... a = attr.ib()
(Attribute(name='a', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, metadata=mappingproxy({}), type=None, converter=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 <https://en.wikipedia.org/wiki/Syntactic_sugar>`_ for::
def original_f():
pass
f = a(b(original_f))
Wrapping the Decorator
----------------------
A more elegant way can be to wrap ``attrs`` altogether and build a class `DSL <https://en.wikipedia.org/wiki/Domain-specific_language>`_ on top of it.
An example for that is the package `environ_config <https://github.com/hynek/environ_config>`_ that uses ``attrs`` under the hood to define environment-based configurations declaratively without exposing ``attrs`` APIs at all.
Types
-----
``attrs`` offers two ways of attaching type information to attributes:
- `PEP 526 <https://www.python.org/dev/peps/pep-0526/>`_ annotations on Python 3.6 and later,
- and the *type* argument to :func:`attr.ib`.
This information is available to you:
.. doctest::
>>> import attr
>>> @attr.s
... class C(object):
... x: int = attr.ib()
... y = attr.ib(type=str)
>>> attr.fields(C).x.type
<class 'int'>
>>> attr.fields(C).y.type
<class 'str'>
Currently, ``attrs`` doesn't do anything with this information but it's very useful if you'd like to write your own validators or serializers!
.. _extending_metadata:
Metadata
--------
If you're the author of a third-party library with ``attrs`` integration, you may want to take advantage of attribute metadata.
Here are some tips for effective use of metadata:
- Try making your metadata keys and values immutable.
This keeps the entire ``Attribute`` instances immutable too.
- To avoid metadata key collisions, consider exposing your metadata keys from your modules.::
from mylib import MY_METADATA_KEY
@attr.s
class C(object):
x = attr.ib(metadata={MY_METADATA_KEY: 1})
Metadata should be composable, so consider supporting this approach even if you decide implementing your metadata in one of the following ways.
- Expose ``attr.ib`` wrappers for your specific metadata.
This is a more graceful approach if your users don't require metadata from other libraries.
.. doctest::
>>> MY_TYPE_METADATA = '__my_type_metadata'
>>>
>>> def typed(cls, default=attr.NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, convert=None, metadata={}):
... metadata = dict() if not metadata else metadata
... metadata[MY_TYPE_METADATA] = cls
... return attr.ib(default, validator, repr, cmp, hash, init, convert, metadata)
>>>
>>> @attr.s
... class C(object):
... x = typed(int, default=1, init=False)
>>> attr.fields(C).x.metadata[MY_TYPE_METADATA]
<class 'int'>

View File

@ -0,0 +1,63 @@
Glossary
========
.. glossary::
dict classes
A regular class whose attributes are stored in the ``__dict__`` attribute of every single instance.
This is quite wasteful especially for objects with very few data attributes and the space consumption can become significant when creating large numbers of instances.
This is the type of class you get by default both with and without ``attrs``.
slotted classes
A class that has no ``__dict__`` attribute and `defines <https://docs.python.org/3/reference/datamodel.html#slots>`_ its attributes in a ``__slots__`` attribute instead.
In ``attrs``, they are created by passing ``slots=True`` to ``@attr.s``.
Their main advantage is that they use less memory on CPython [#pypy]_.
However they also come with a bunch of possibly surprising gotchas:
- Slotted classes don't allow for any other attribute to be set except for those defined in one of the class' hierarchies ``__slots__``:
.. doctest::
>>> import attr
>>> @attr.s(slots=True)
... class Coordinates(object):
... x = attr.ib()
... y = attr.ib()
...
>>> c = Coordinates(x=1, y=2)
>>> c.z = 3
Traceback (most recent call last):
...
AttributeError: 'Coordinates' object has no attribute 'z'
- Slotted classes can inherit from other classes just like non-slotted classes, but some of the benefits of slotted classes are lost if you do that.
If you must inherit from other classes, try to inherit only from other slot classes.
- Using :mod:`pickle` with slotted classes requires pickle protocol 2 or greater.
Python 2 uses protocol 0 by default so the protocol needs to be specified.
Python 3 uses protocol 3 by default.
You can support protocol 0 and 1 by implementing :meth:`__getstate__ <object.__getstate__>` and :meth:`__setstate__ <object.__setstate__>` methods yourself.
Those methods are created for frozen slotted classes because they won't pickle otherwise.
`Think twice <https://www.youtube.com/watch?v=7KnfGDajDQw>`_ before using :mod:`pickle` though.
- As always with slotted classes, you must specify a ``__weakref__`` slot if you wish for the class to be weak-referenceable.
Here's how it looks using ``attrs``:
.. doctest::
>>> import weakref
>>> @attr.s(slots=True)
... class C(object):
... __weakref__ = attr.ib(init=False, hash=False, repr=False, cmp=False)
... x = attr.ib()
>>> c = C(1)
>>> weakref.ref(c)
<weakref at 0x...; to 'C' at 0x...>
- Since it's currently impossible to make a class slotted after it's created, ``attrs`` has to replace your class with a new one.
While it tries to do that as graciously as possible, certain metaclass features like ``__init_subclass__`` do not work with slotted classes.
.. [#pypy] On PyPy, there is no memory advantage in using slotted classes.

View File

@ -0,0 +1,56 @@
Hashing
=======
.. warning::
The overarching theme is to never set the ``@attr.s(hash=X)`` parameter yourself.
Leave it at ``None`` which means that ``attrs`` will do the right thing for you, depending on the other parameters:
- If you want to make objects hashable by value: use ``@attr.s(frozen=True)``.
- If you want hashing and comparison by object identity: use ``@attr.s(cmp=False)``
Setting ``hash`` yourself can have unexpected consequences so we recommend to tinker with it only if you know exactly what you're doing.
Under certain circumstances, it's necessary for objects to be *hashable*.
For example if you want to put them into a :class:`set` or if you want to use them as keys in a :class:`dict`.
The *hash* of an object is an integer that represents the contents of an object.
It can be obtained by calling :func:`hash` on an object and is implemented by writing a ``__hash__`` method for your class.
``attrs`` will happily write a ``__hash__`` method you [#fn1]_, however it will *not* do so by default.
Because according to the definition_ from the official Python docs, the returned hash has to fullfil certain constraints:
#. Two objects that are equal, **must** have the same hash.
This means that if ``x == y``, it *must* follow that ``hash(x) == hash(y)``.
By default, Python classes are compared *and* hashed by their :func:`id`.
That means that every instance of a class has a different hash, no matter what attributes it carries.
It follows that the moment you (or ``attrs``) change the way equality is handled by implementing ``__eq__`` which is based on attribute values, this constraint is broken.
For that reason Python 3 will make a class that has customized equality unhashable.
Python 2 on the other hand will happily let you shoot your foot off.
Unfortunately ``attrs`` currently mimics Python 2's behavior for backward compatibility reasons if you set ``hash=False``.
The *correct way* to achieve hashing by id is to set ``@attr.s(cmp=False)``.
Setting ``@attr.s(hash=False)`` (that implies ``cmp=True``) is almost certainly a *bug*.
#. If two object are not equal, their hash **should** be different.
While this isn't a requirement from a standpoint of correctness, sets and dicts become less effective if there are a lot of identical hashes.
The worst case is when all objects have the same hash which turns a set into a list.
#. The hash of an object **must not** change.
If you create a class with ``@attr.s(frozen=True)`` this is fullfilled by definition, therefore ``attrs`` will write a ``__hash__`` function for you automatically.
You can also force it to write one with ``hash=True`` but then it's *your* responsibility to make sure that the object is not mutated.
This point is the reason why mutable structures like lists, dictionaries, or sets aren't hashable while immutable ones like tuples or frozensets are:
point 1 and 2 require that the hash changes with the contents but point 3 forbids it.
For a more thorough explanation of this topic, please refer to this blog post: `Python Hashes and Equality`_.
.. [#fn1] The hash is computed by hashing a tuple that consists of an unique id for the class plus all attribute values.
.. _definition: https://docs.python.org/3/glossary.html#term-hashable
.. _`Python Hashes and Equality`: https://hynek.me/articles/hashes-and-equality/

View File

@ -0,0 +1,100 @@
.. _how:
How Does It Work?
=================
Boilerplate
-----------
``attrs`` certainly isn't the first library that aims to simplify class definition in Python.
But its **declarative** approach combined with **no runtime overhead** lets it stand out.
Once you apply the ``@attr.s`` decorator to a class, ``attrs`` searches the class object for instances of ``attr.ib``\ s.
Internally they're a representation of the data passed into ``attr.ib`` along with a counter to preserve the order of the attributes.
In order to ensure that sub-classing works as you'd expect it to work, ``attrs`` also walks the class hierarchy and collects the attributes of all super-classes.
Please note that ``attrs`` does *not* call ``super()`` *ever*.
It will write dunder methods to work on *all* of those attributes which also has performance benefits due to fewer function calls.
Once ``attrs`` knows what attributes it has to work on, it writes the requested dunder methods and -- depending on whether you wish to have a :term:`dict <dict classes>` or :term:`slotted <slotted classes>` class -- creates a new class for you (``slots=True``) or attaches them to the original class (``slots=False``).
While creating new classes is more elegant, we've run into several edge cases surrounding metaclasses that make it impossible to go this route unconditionally.
To be very clear: if you define a class with a single attribute without a default value, the generated ``__init__`` will look *exactly* how you'd expect:
.. doctest::
>>> import attr, inspect
>>> @attr.s
... class C(object):
... x = attr.ib()
>>> print(inspect.getsource(C.__init__))
def __init__(self, x):
self.x = x
<BLANKLINE>
No magic, no meta programming, no expensive introspection at runtime.
****
Everything until this point happens exactly *once* when the class is defined.
As soon as a class is done, it's done.
And it's just a regular Python class like any other, except for a single ``__attrs_attrs__`` attribute that can be used for introspection or for writing your own tools and decorators on top of ``attrs`` (like :func:`attr.asdict`).
And once you start instantiating your classes, ``attrs`` is out of your way completely.
This **static** approach was very much a design goal of ``attrs`` and what I strongly believe makes it distinct.
.. _how-frozen:
Immutability
------------
In order to give you immutability, ``attrs`` will attach a ``__setattr__`` method to your class that raises a :exc:`attr.exceptions.FrozenInstanceError` whenever anyone tries to set an attribute.
Depending on whether of not a class is a dict class or a slots class, ``attrs`` uses a different technique to circumvent that limitation in the ``__init__`` method.
Once constructed, frozen instances don't differ in any way from regular ones except that you cannot change its attributes.
Dict Classes
++++++++++++
Dict classes -- i.e. regular classes -- simply assign the value directly into the class' eponymous ``__dict__`` (and there's nothing we can do to stop the user to do the same).
The performance impact is negligible.
Slots Classes
+++++++++++++
Slots classes are more complicated.
Here it uses (an aggressively cached) :meth:`object.__setattr__` to set your attributes.
This is (still) slower than a plain assignment:
.. code-block:: none
$ pyperf timeit --rigorous \
-s "import attr; C = attr.make_class('C', ['x', 'y', 'z'], slots=True)" \
"C(1, 2, 3)"
........................................
Median +- std dev: 378 ns +- 12 ns
$ pyperf timeit --rigorous \
-s "import attr; C = attr.make_class('C', ['x', 'y', 'z'], slots=True, frozen=True)" \
"C(1, 2, 3)"
........................................
Median +- std dev: 676 ns +- 16 ns
So on a standard notebook the difference is about 300 nanoseconds (1 second is 1,000,000,000 nanoseconds).
It's certainly something you'll feel in a hot loop but shouldn't matter in normal code.
Pick what's more important to you.
Summary
+++++++
You should avoid to instantiate lots of frozen slotted classes (i.e. ``@attr.s(slots=True, frozen=True)``) in performance-critical code.
Frozen dict classes have barely a performance impact, unfrozen slotted classes are even *faster* than unfrozen dict classes (i.e. regular classes).

89
third_party/python/attrs/docs/index.rst vendored Normal file
View File

@ -0,0 +1,89 @@
======================================
``attrs``: Classes Without Boilerplate
======================================
Release v\ |release| (:doc:`What's new? <changelog>`).
.. include:: ../README.rst
:start-after: teaser-begin
:end-before: -spiel-end-
Getting Started
===============
``attrs`` is a Python-only package `hosted on PyPI <https://pypi.org/project/attrs/>`_.
The recommended installation method is `pip <https://pip.pypa.io/en/stable/>`_-installing into a `virtualenv <https://hynek.me/articles/virtualenv-lives/>`_:
.. code-block:: console
$ pip install attrs
The next three steps should bring you up and running in no time:
- :doc:`overview` will show you a simple example of ``attrs`` in action and introduce you to its philosophy.
Afterwards, you can start writing your own classes, understand what drives ``attrs``'s design, and know what ``@attr.s`` and ``attr.ib()`` stand for.
- :doc:`examples` will give you a comprehensive tour of ``attrs``'s features.
After reading, you will know about our advanced features and how to use them.
- Finally :doc:`why` gives you a rundown of potential alternatives and why we think ``attrs`` is superior.
Yes, we've heard about ``namedtuple``\ s!
- If at any point you get confused by some terminology, please check out our :doc:`glossary`.
If you need any help while getting started, feel free to use the ``python-attrs`` tag on `StackOverflow <https://stackoverflow.com/questions/tagged/python-attrs>`_ and someone will surely help you out!
Day-to-Day Usage
================
- Once you're comfortable with the concepts, our :doc:`api` contains all information you need to use ``attrs`` to its fullest.
- Instance initialization is one of ``attrs`` key feature areas.
Our goal is to relieve you from writing as much code as possible.
:doc:`init` gives you an overview what ``attrs`` has to offer and explains some related philosophies we believe in.
- If you want to put objects into sets or use them as keys in dictionaries, they have to be hashable.
The simplest way to do that is to use frozen classes, but the topic is more complex than it seems and :doc:`hashing` will give you a primer on what to look out for.
- ``attrs`` is built for extension from the ground up.
:doc:`extending` will show you the affordances it offers and how to make it a building block of your own projects.
.. include:: ../README.rst
:start-after: -testimonials-
:end-before: -end-
.. include:: ../README.rst
:start-after: -project-information-
.. toctree::
:maxdepth: 1
license
backward-compatibility
contributing
changelog
----
Full Table of Contents
======================
.. toctree::
:maxdepth: 2
overview
why
examples
init
hashing
api
extending
how-does-it-work
glossary
Indices and tables
==================
* :ref:`genindex`
* :ref:`search`

354
third_party/python/attrs/docs/init.rst vendored Normal file
View File

@ -0,0 +1,354 @@
Initialization
==============
In Python, instance intialization happens in the ``__init__`` method.
Generally speaking, you should keep as little logic as possible in it, and you should think about what the class needs and not how it is going to be instantiated.
Passing complex objects into ``__init__`` and then using them to derive data for the class unnecessarily couples your new class with the old class which makes it harder to test and also will cause problems later.
So assuming you use an ORM and want to extract 2D points from a row object, do not write code like this::
class Point(object):
def __init__(self, database_row):
self.x = database_row.x
self.y = database_row.y
pt = Point(row)
Instead, write a :func:`classmethod` that will extract it for you::
@attr.s
class Point(object):
x = attr.ib()
y = attr.ib()
@classmethod
def from_row(cls, row):
return cls(row.x, row.y)
pt = Point.from_row(row)
Now you can instantiate ``Point``\ s without creating fake row objects in your tests and you can have as many smart creation helpers as you want, in case more data sources appear.
For similar reasons, we strongly discourage from patterns like::
pt = Point(**row.attributes)
which couples your classes to the data model.
Try to design your classes in a way that is clean and convenient to use -- not based on your database format.
The database format can change anytime and you're stuck with a bad class design that is hard to change.
Embrace classmethods as a filter between reality and what's best for you to work with.
If you look for object serialization, there's a bunch of projects listed on our ``attrs`` extensions `Wiki page`_.
Some of them even support nested schemas.
Private Attributes
------------------
One thing people tend to find confusing is the treatment of private attributes that start with an underscore.
``attrs`` follows the doctrine that `there is no such thing as a private argument`_ and strips the underscores from the name when writing the ``__init__`` method signature:
.. doctest::
>>> import inspect, attr
>>> @attr.s
... class C(object):
... _x = attr.ib()
>>> inspect.signature(C.__init__)
<Signature (self, x) -> None>
There really isn't a right or wrong, it's a matter of taste.
But it's important to be aware of it because it can lead to surprising syntax errors:
.. doctest::
>>> @attr.s
... class C(object):
... _1 = attr.ib()
Traceback (most recent call last):
...
SyntaxError: invalid syntax
In this case a valid attribute name ``_1`` got transformed into an invalid argument name ``1``.
Defaults
--------
Sometimes you don't want to pass all attribute values to a class.
And sometimes, certain attributes aren't even intended to be passed but you want to allow for customization anyways for easier testing.
This is when default values come into play:
.. doctest::
>>> import attr
>>> @attr.s
... class C(object):
... a = attr.ib(default=42)
... b = attr.ib(default=attr.Factory(list))
... c = attr.ib(factory=list) # syntactic sugar for above
... d = attr.ib()
... @d.default
... def _any_name_except_a_name_of_an_attribute(self):
... return {}
>>> C()
C(a=42, b=[], c=[], d={})
It's important that the decorated method -- or any other method or property! -- doesn't have the same name as the attribute, otherwise it would overwrite the attribute definition.
Please note that as with function and method signatures, ``default=[]`` will *not* do what you may think it might do:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(default=[])
>>> i = C()
>>> j = C()
>>> i.x.append(42)
>>> j.x
[42]
This is why ``attrs`` comes with factory options.
.. warning::
Please note that the decorator based defaults have one gotcha:
they are executed when the attribute is set, that means depending on the order of attributes, the ``self`` object may not be fully initialized when they're called.
Therefore you should use ``self`` as little as possible.
Even the smartest of us can `get confused`_ by what happens if you pass partially initialized objects around.
.. _validators:
Validators
----------
Another thing that definitely *does* belong into ``__init__`` is checking the resulting instance for invariants.
This is why ``attrs`` has the concept of validators.
Decorator
~~~~~~~~~
The most straightforward way is using the attribute's ``validator`` method as a decorator.
The method has to accept three arguments:
#. the *instance* that's being validated (aka ``self``),
#. 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.
>>> @attr.s
... class C(object):
... x = attr.ib()
... @x.validator
... def _check_x(self, attribute, value):
... if value > 42:
... raise ValueError("x must be smaller or equal to 42")
>>> C(42)
C(x=42)
>>> C(43)
Traceback (most recent call last):
...
ValueError: x must be smaller or equal to 42
Again, it's important that the decorated method doesn't have the same name as the attribute.
Callables
~~~~~~~~~
If you want to re-use your validators, you should have a look at the ``validator`` argument to :func:`attr.ib()`.
It takes either a callable or a list of callables (usually functions) and treats them as validators that receive the same arguments as with the decorator approach.
Since the validators 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=[attr.validators.instance_of(int),
... 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'!
This example also shows of some syntactic sugar for using the :func:`attr.validators.and_` validator: if you pass a list, all validators have to pass.
``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 <api_validators>` 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 <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None), <type 'int'>, '42')
Of course you can mix and match the two approaches at your convenience.
If you define validators both ways for an attribute, they are both ran:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib(validator=attr.validators.instance_of(int))
... @x.validator
... def fits_byte(self, attribute, value):
... if not 0 <= value < 256:
... raise ValueError("value out of bounds")
>>> C(128)
C(x=128)
>>> C("128")
Traceback (most recent call last):
...
TypeError: ("'x' must be <class 'int'> (got '128' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_of validator for type <class 'int'>>, <function fits_byte at 0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=one), <class 'int'>, '128')
>>> C(256)
Traceback (most recent call last):
...
ValueError: value out of bounds
And finally you can disable validators globally:
>>> attr.set_run_validators(False)
>>> C("128")
C(x='128')
>>> attr.set_run_validators(True)
>>> C("128")
Traceback (most recent call last):
...
TypeError: ("'x' must be <class 'int'> (got '128' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_of validator for type <class 'int'>>, <function fits_byte at 0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=None), <class 'int'>, '128')
.. _converters:
Converters
----------
Finally, sometimes you may want to normalize the values coming in.
For that ``attrs`` comes with converters.
Attributes can have a ``converter`` 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(converter=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 at least 0.")
>>> @attr.s
... class C(object):
... x = attr.ib(converter=int, validator=validate_x)
>>> o = C("0")
>>> o.x
0
>>> C("-1")
Traceback (most recent call last):
...
ValueError: x must be at least 0.
Arguably, you can abuse converters as one-argument validators:
.. doctest::
>>> C("x")
Traceback (most recent call last):
...
ValueError: invalid literal for int() with base 10: 'x'
Post-Init Hook
--------------
Generally speaking, the moment you think that you need finer control over how your class is instantiated than what ``attrs`` offers, it's usually best to use a classmethod factory or to apply the `builder pattern <https://en.wikipedia.org/wiki/Builder_pattern>`_.
However, sometimes you need to do that one quick thing after your class is initialized.
And for that ``attrs`` offers the ``__attrs_post_init__`` hook that is automatically detected and run after ``attrs`` is done initializing your instance:
.. doctest::
>>> @attr.s
... class C(object):
... x = attr.ib()
... y = attr.ib(init=False)
... def __attrs_post_init__(self):
... self.y = self.x + 1
>>> C(1)
C(x=1, y=2)
Please note that you can't directly set attributes on frozen classes:
.. doctest::
>>> @attr.s(frozen=True)
... class FrozenBroken(object):
... x = attr.ib()
... y = attr.ib(init=False)
... def __attrs_post_init__(self):
... self.y = self.x + 1
>>> FrozenBroken(1)
Traceback (most recent call last):
...
attr.exceptions.FrozenInstanceError: can't set attribute
If you need to set attributes on a frozen class, you'll have to resort to the :ref:`same trick <how-frozen>` as ``attrs`` and use :meth:`object.__setattr__`:
.. doctest::
>>> @attr.s(frozen=True)
... class Frozen(object):
... x = attr.ib()
... y = attr.ib(init=False)
... def __attrs_post_init__(self):
... object.__setattr__(self, "y", self.x + 1)
>>> Frozen(1)
Frozen(x=1, y=2)
.. _`Wiki page`: https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs
.. _`get confused`: https://github.com/python-attrs/attrs/issues/289
.. _`there is no such thing as a private argument`: https://github.com/hynek/characteristic/issues/6

View File

@ -0,0 +1,8 @@
===================
License and Credits
===================
``attrs`` is licensed under the `MIT <https://choosealicense.com/licenses/mit/>`_ license.
The full license text can be also found in the `source code repository <https://github.com/python-attrs/attrs/blob/master/LICENSE>`_.
.. include:: ../AUTHORS.rst

View File

@ -0,0 +1,87 @@
========
Overview
========
In order to fulfill its ambitious goal of bringing back the joy to writing classes, it gives you a class decorator and a way to declaratively define the attributes on that class:
.. include:: ../README.rst
:start-after: -code-begin-
:end-before: -testimonials-
.. _philosophy:
Philosophy
==========
**It's about regular classes.**
``attrs`` is for creating well-behaved classes with a type, attributes, methods, and everything that comes with a class.
It can be used for data-only containers like ``namedtuple``\ s or ``types.SimpleNamespace`` but they're just a sub-genre of what ``attrs`` is good for.
**The class belongs to the users.**
You define a class and ``attrs`` adds static methods to that class based on the attributes you declare.
The end.
It doesn't add metaclasses.
It doesn't add classes you've never heard of to your inheritance tree.
An ``attrs`` class in runtime is indistiguishable from a regular class: because it *is* a regular class with a few boilerplate-y methods attached.
**Be light on API impact.**
As convenient as it seems at first, ``attrs`` will *not* tack on any methods to your classes save the dunder ones.
Hence all the useful :ref:`tools <helpers>` that come with ``attrs`` live in functions that operate on top of instances.
Since they take an ``attrs`` instance as their first argument, you can attach them to your classes with one line of code.
**Performance matters.**
``attrs`` runtime impact is very close to zero because all the work is done when the class is defined.
Once you're instantiating it, ``attrs`` is out of the picture completely.
**No surprises.**
``attrs`` creates classes that arguably work the way a Python beginner would reasonably expect them to work.
It doesn't try to guess what you mean because explicit is better than implicit.
It doesn't try to be clever because software shouldn't be clever.
Check out :doc:`how-does-it-work` if you'd like to know how it achieves all of the above.
What ``attrs`` Is Not
=====================
``attrs`` does *not* invent some kind of magic system that pulls classes out of its hat using meta classes, runtime introspection, and shaky interdependencies.
All ``attrs`` does is:
1. take your declaration,
2. write dunder methods based on that information,
3. and attach them to your class.
It does *nothing* dynamic at runtime, hence zero runtime overhead.
It's still *your* class.
Do with it as you please.
On the ``attr.s`` and ``attr.ib`` Names
=======================================
The ``attr.s`` decorator and the ``attr.ib`` function aren't any obscure abbreviations.
They are a *concise* and highly *readable* way to write ``attrs`` and ``attrib`` with an *explicit namespace*.
At first, some people have a negative gut reaction to that; resembling the reactions to Python's significant whitespace.
And as with that, once one gets used to it, the readability and explicitness of that API prevails and delights.
For those who can't swallow that API at all, ``attrs`` comes with serious business aliases: ``attr.attrs`` and ``attr.attrib``.
Therefore, the following class definition is identical to the previous one:
.. doctest::
>>> from attr import attrs, attrib, Factory
>>> @attrs
... class SomeClass(object):
... a_number = attrib(default=42)
... list_of_numbers = attrib(default=Factory(list))
...
... def hard_math(self, another_number):
... return self.a_number + sum(self.list_of_numbers) * another_number
>>> SomeClass(1, [1, 2, 3])
SomeClass(a_number=1, list_of_numbers=[1, 2, 3])
Use whichever variant fits your taste better.

271
third_party/python/attrs/docs/why.rst vendored Normal file
View File

@ -0,0 +1,271 @@
.. _why:
Why not…
========
If you'd like third party's account why ``attrs`` is great, have a look at Glyph's `The One Python Library Everyone Needs <https://glyph.twistedmatrix.com/2016/08/attrs.html>`_!
…tuples?
--------
Readability
^^^^^^^^^^^
What makes more sense while debugging::
Point(x=1, y=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 run into mysterious tuples you had no idea what the hell they meant while debugging, you're much smarter than yours truly.
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: https://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?
-------------
:func:`collections.namedtuple`\ s are tuples with names, not classes. [#history]_
Since writing classes is tiresome in Python, every now and then someone discovers all the typing they could save and gets really excited.
However that convenience comes at a price.
The most obvious difference between ``namedtuple``\ s and ``attrs``-based classes is that the latter are type-sensitive:
.. doctest::
>>> import attr
>>> C1 = attr.make_class("C1", ["a"])
>>> C2 = attr.make_class("C2", ["a"])
>>> i1 = C1(1)
>>> i2 = C2(1)
>>> i1.a == i2.a
True
>>> i1 == i2
False
…while a ``namedtuple`` is *intentionally* `behaving like a tuple`_ which means the type of a tuple is *ignored*:
.. doctest::
>>> from collections import namedtuple
>>> NT1 = namedtuple("NT1", "a")
>>> NT2 = namedtuple("NT2", "b")
>>> t1 = NT1(1)
>>> t2 = NT2(1)
>>> t1 == t2 == (1,)
True
Other often surprising behaviors include:
- Since they are a subclass of tuples, ``namedtuple``\ s have a length and are both iterable and indexable.
That's not what you'd expect from a class and is likely to shadow subtle typo bugs.
- Iterability also implies that it's easy to accidentally unpack a ``namedtuple`` which leads to hard-to-find bugs. [#iter]_
- ``namedtuple``\ s have their methods *on your instances* whether you like it or not. [#pollution]_
- ``namedtuple``\ s are *always* immutable.
Not only does that mean that you can't decide for yourself whether your instances should be immutable or not, it also means that if you want to influence your class' initialization (validation? default values?), you have to implement :meth:`__new__() <object.__new__>` which is a particularly hacky and error-prone requirement for a very common problem. [#immutable]_
- To attach methods to a ``namedtuple`` you have to subclass it.
And if you follow the standard library documentation's recommendation of::
class Point(namedtuple('Point', ['x', 'y'])):
# ...
you end up with a class that has *two* ``Point``\ s in its :attr:`__mro__ <class.__mro__>`: ``[<class 'point.Point'>, <class 'point.Point'>, <type 'tuple'>, <type 'object'>]``.
That's not only confusing, it also has very practical consequences:
for example if you create documentation that includes class hierarchies like `Sphinx's autodoc <http://www.sphinx-doc.org/en/stable/ext/autodoc.html>`_ with ``show-inheritance``.
Again: common problem, hacky solution with confusing fallout.
All these things make ``namedtuple``\ s a particularly poor choice for public APIs because all your objects are irrevocably tainted.
With ``attrs`` your users won't notice a difference because it creates regular, well-behaved classes.
.. admonition:: Summary
If you want a *tuple with names*, by all means: go for a ``namedtuple``. [#perf]_
But if you want a class with methods, you're doing yourself a disservice by relying on a pile of hacks that requires you to employ even more hacks as your requirements expand.
Other than that, ``attrs`` also adds nifty features like validators, converters, and (mutable!) default values.
.. rubric:: Footnotes
.. [#history] The word is that ``namedtuple``\ s were added to the Python standard library as a way to make tuples in return values more readable.
And indeed that is something you see throughout the standard library.
Looking at what the makers of ``namedtuple``\ s use it for themselves is a good guideline for deciding on your own use cases.
.. [#pollution] ``attrs`` only adds a single attribute: ``__attrs_attrs__`` for introspection.
All helpers are functions in the ``attr`` package.
Since they take the instance as first argument, you can easily attach them to your classes under a name of your own choice.
.. [#iter] :func:`attr.astuple` can be used to get that behavior in ``attrs`` on *explicit demand*.
.. [#immutable] ``attrs`` offers *optional* immutability through the ``frozen`` keyword.
.. [#perf] Although ``attrs`` would serve you just as well!
Since both employ the same method of writing and compiling Python code for you, the performance penalty is negligible at worst and in some cases ``attrs`` is even faster if you use ``slots=True`` (which is generally a good idea anyway).
.. _behaving like a tuple: https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences
…Data Classes?
--------------
`PEP 557 <https://www.python.org/dev/peps/pep-0557/>`_ added Data Classes to `Python 3.7 <https://docs.python.org/3.7/whatsnew/3.7.html#pep-557-data-classes>`_ that resemble ``attrs`` in many ways.
They are the result of the Python community's `wish <https://mail.python.org/pipermail/python-ideas/2017-May/045618.html>`_ to have an easier way to write classes in the standard library that doesn't carry the problems of ``namedtuple``\ s.
To that end, ``attrs`` and its developers were involved in the PEP process and while we may disagree with some minor decisions that have been made, it's a fine library and if it stops you from abusing ``namedtuple``\ s, they are a huge win.
Nevertheless, there are still reasons to prefer ``attrs`` over Data Classes whose relevancy depends on your circumstances:
- ``attrs`` supports all maintream Python versions, including CPython 2.7 and PyPy.
- Data Classes are intentionally less powerful than ``attrs``.
There is a long list of features that were sacrificed for the sake of simplicity and while the most obvious ones are validators, converters, and ``__slots__``, it permeates throughout all APIs.
On the other hand, Data Classes currently do not offer any significant feature that ``attrs`` doesn't already have.
- ``attrs`` can and will move faster.
We are not bound to any release schedules and we have a clear deprecation policy.
One of the `reasons <https://www.python.org/dev/peps/pep-0557/#why-not-just-use-attrs>`_ to not vendor ``attrs`` in the standard library was to not impede ``attrs``'s future developement.
…dicts?
-------
Dictionaries are not for fixed fields.
If you have a dict, it maps something to something else.
You should be able to add and remove values.
``attrs`` lets you be specific about those expectations; a dictionary does not.
It gives you a named entity (the class) in your code, which lets you explain in other places whether you take a parameter of that class or return a value of that class.
In other words: if your dict has a fixed and known set of keys, it is an object, not a hash.
So if you never iterate over the keys of a dict, you should use a proper class.
…hand-written classes?
----------------------
While we're fans of all things artisanal, writing the same nine methods again and again doesn't qualify.
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 roughly
.. 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.__class__, 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__``?
It also should be noted that ``attrs`` is not an all-or-nothing solution.
You can freely choose which features you want and disable those that you want more control over:
.. doctest::
>>> @attr.s(repr=False)
... class SmartClass(object):
... a = attr.ib()
... b = attr.ib()
...
... def __repr__(self):
... return "<SmartClass(a=%d)>" % (self.a,)
>>> SmartClass(1, 2)
<SmartClass(a=1)>
.. admonition:: Summary
If you don't care and like typing, we're not gonna stop you.
However it takes a lot of bias and determined rationalization to claim that ``attrs`` raises the mental burden on a project given how difficult it is to find the important bits in a hand-written class and how annoying it is to ensure you've copy-pasted your code correctly over all your classes.
In any case, if you ever get sick of the repetitiveness and drowning important code in a sea of boilerplate, ``attrs`` will be waiting for you.

12
third_party/python/attrs/moz.yaml vendored Normal file
View File

@ -0,0 +1,12 @@
---
schema: 1
description: Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols.
url: "http://www.attrs.org/"
release: "18.1.0"
licenses:
- MIT
bugzilla:
product: Taskcluster
component: Task Configuration
vendoring:
url: https://pypi.org/packages/source/a/attrs/attrs-18.1.0.tar.gz

27
third_party/python/attrs/pyproject.toml vendored Normal file
View File

@ -0,0 +1,27 @@
[tool.towncrier]
package = "attr"
package_dir = "src"
filename = "CHANGELOG.rst"
template = "changelog.d/towncrier_template.rst"
issue_format = "`#{issue} <https://github.com/python-attrs/attrs/issues/{issue}>`_"
directory = "changelog.d"
title_format = "{version} ({project_date})"
underlines = ["-", "^"]
[[tool.towncrier.section]]
path = ""
[[tool.towncrier.type]]
directory = "breaking"
name = "Backward-incompatible Changes"
showcontent = true
[[tool.towncrier.type]]
directory = "deprecation"
name = "Deprecations"
showcontent = true
[[tool.towncrier.type]]
directory = "change"
name = "Changes"
showcontent = true

26
third_party/python/attrs/setup.cfg vendored Normal file
View File

@ -0,0 +1,26 @@
[bdist_wheel]
universal = 1
[metadata]
license_file = LICENSE
[tool:pytest]
minversion = 3.0
strict = true
addopts = -ra
testpaths = tests
filterwarnings =
once::Warning
[isort]
atomic = true
lines_after_imports = 2
lines_between_types = 1
multi_line_output = 5
not_skip = __init__.py
known_first_party = attr
[egg_info]
tag_build =
tag_date = 0

112
third_party/python/attrs/setup.py vendored Normal file
View File

@ -0,0 +1,112 @@
import codecs
import os
import re
from setuptools import find_packages, setup
###############################################################################
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.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Libraries :: Python Modules",
]
INSTALL_REQUIRES = []
EXTRAS_REQUIRE = {
"docs": [
"sphinx",
"zope.interface",
],
"tests": [
"coverage",
"hypothesis",
"pympler",
"pytest",
"six",
"zope.interface",
],
}
EXTRAS_REQUIRE["dev"] = EXTRAS_REQUIRE["tests"] + EXTRAS_REQUIRE["docs"]
###############################################################################
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))
VERSION = find_meta("version")
URI = find_meta("uri")
LONG = (
read("README.rst") + "\n\n" +
"Release Information\n" +
"===================\n\n" +
re.search("(\d+.\d.\d \(.*?\)\n.*?)\n\n\n----\n\n\n",
read("CHANGELOG.rst"), re.S).group(1) +
"\n\n`Full changelog " +
"<{uri}en/stable/changelog.html>`_.\n\n".format(uri=URI) +
read("AUTHORS.rst")
)
if __name__ == "__main__":
setup(
name=NAME,
description=find_meta("description"),
license=find_meta("license"),
url=URI,
version=VERSION,
author=find_meta("author"),
author_email=find_meta("email"),
maintainer=find_meta("author"),
maintainer_email=find_meta("email"),
keywords=KEYWORDS,
long_description=LONG,
packages=PACKAGES,
package_dir={"": "src"},
zip_safe=False,
classifiers=CLASSIFIERS,
install_requires=INSTALL_REQUIRES,
extras_require=EXTRAS_REQUIRE,
)

View File

@ -0,0 +1,57 @@
from __future__ import absolute_import, division, print_function
from functools import partial
from . import converters, exceptions, filters, validators
from ._config import get_run_validators, set_run_validators
from ._funcs import asdict, assoc, astuple, evolve, has
from ._make import (
NOTHING, Attribute, Factory, attrib, attrs, fields, fields_dict,
make_class, validate
)
__version__ = "18.1.0"
__title__ = "attrs"
__description__ = "Classes Without Boilerplate"
__uri__ = "http://www.attrs.org/"
__doc__ = __description__ + " <" + __uri__ + ">"
__author__ = "Hynek Schlawack"
__email__ = "hs@ox.cx"
__license__ = "MIT"
__copyright__ = "Copyright (c) 2015 Hynek Schlawack"
s = attributes = attrs
ib = attr = attrib
dataclass = partial(attrs, auto_attribs=True) # happy Easter ;)
__all__ = [
"Attribute",
"Factory",
"NOTHING",
"asdict",
"assoc",
"astuple",
"attr",
"attrib",
"attributes",
"attrs",
"converters",
"evolve",
"exceptions",
"fields",
"fields_dict",
"filters",
"get_run_validators",
"has",
"ib",
"make_class",
"s",
"set_run_validators",
"validate",
"validators",
]

View File

@ -0,0 +1,146 @@
from __future__ import absolute_import, division, print_function
import platform
import sys
import types
import warnings
PY2 = sys.version_info[0] == 2
PYPY = platform.python_implementation() == "PyPy"
if PYPY or sys.version_info[:2] >= (3, 6):
ordered_dict = dict
else:
from collections import OrderedDict
ordered_dict = OrderedDict
if PY2:
from UserDict import IterableUserDict
# We 'bundle' isclass instead of using inspect as importing inspect is
# fairly expensive (order of 10-15 ms for a modern machine in 2016)
def isclass(klass):
return isinstance(klass, (type, types.ClassType))
# TYPE is used in exceptions, repr(int) is different on Python 2 and 3.
TYPE = "type"
def iteritems(d):
return d.iteritems()
# Python 2 is bereft of a read-only dict proxy, so we make one!
class ReadOnlyDict(IterableUserDict):
"""
Best-effort read-only dict wrapper.
"""
def __setitem__(self, key, val):
# We gently pretend we're a Python 3 mappingproxy.
raise TypeError("'mappingproxy' object does not support item "
"assignment")
def update(self, _):
# We gently pretend we're a Python 3 mappingproxy.
raise AttributeError("'mappingproxy' object has no attribute "
"'update'")
def __delitem__(self, _):
# We gently pretend we're a Python 3 mappingproxy.
raise TypeError("'mappingproxy' object does not support item "
"deletion")
def clear(self):
# We gently pretend we're a Python 3 mappingproxy.
raise AttributeError("'mappingproxy' object has no attribute "
"'clear'")
def pop(self, key, default=None):
# We gently pretend we're a Python 3 mappingproxy.
raise AttributeError("'mappingproxy' object has no attribute "
"'pop'")
def popitem(self):
# We gently pretend we're a Python 3 mappingproxy.
raise AttributeError("'mappingproxy' object has no attribute "
"'popitem'")
def setdefault(self, key, default=None):
# We gently pretend we're a Python 3 mappingproxy.
raise AttributeError("'mappingproxy' object has no attribute "
"'setdefault'")
def __repr__(self):
# Override to be identical to the Python 3 version.
return "mappingproxy(" + repr(self.data) + ")"
def metadata_proxy(d):
res = ReadOnlyDict()
res.data.update(d) # We blocked update, so we have to do it like this.
return res
else:
def isclass(klass):
return isinstance(klass, type)
TYPE = "class"
def iteritems(d):
return d.items()
def metadata_proxy(d):
return types.MappingProxyType(dict(d))
def import_ctypes():
"""
Moved into a function for testability.
"""
import ctypes
return ctypes
if not PY2:
def just_warn(*args, **kw):
"""
We only warn on Python 3 because we are not aware of any concrete
consequences of not setting the cell on Python 2.
"""
warnings.warn(
"Missing ctypes. Some features like bare super() or accessing "
"__class__ will not work with slots classes.",
RuntimeWarning,
stacklevel=2,
)
else:
def just_warn(*args, **kw): # pragma: nocover
"""
We only warn on Python 3 because we are not aware of any concrete
consequences of not setting the cell on Python 2.
"""
def make_set_closure_cell():
"""
Moved into a function for testability.
"""
if PYPY: # pragma: no cover
def set_closure_cell(cell, value):
cell.__setstate__((value,))
else:
try:
ctypes = import_ctypes()
set_closure_cell = ctypes.pythonapi.PyCell_Set
set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object)
set_closure_cell.restype = ctypes.c_int
except Exception:
# We try best effort to set the cell, but sometimes it's not
# possible. For example on Jython or on GAE.
set_closure_cell = just_warn
return set_closure_cell
set_closure_cell = make_set_closure_cell()

View File

@ -0,0 +1,23 @@
from __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

View File

@ -0,0 +1,212 @@
from __future__ import absolute_import, division, print_function
import copy
from ._compat import iteritems
from ._make import NOTHING, _obj_setattr, fields
from .exceptions import AttrsAttributeNotFoundError
def asdict(inst, recurse=True, filter=None, dict_factory=dict,
retain_collection_types=False):
"""
Return the ``attrs`` attribute values of *inst* as a dict.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines 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.
:param callable dict_factory: A callable to produce dictionaries from. For
example, to produce ordered dictionaries instead of normal Python
dictionaries, pass in ``collections.OrderedDict``.
:param bool retain_collection_types: Do not convert to ``list`` when
encountering an attribute whose type is ``tuple`` or ``set``. Only
meaningful if ``recurse`` is ``True``.
:rtype: return type of *dict_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.0.0 *dict_factory*
.. versionadded:: 16.1.0 *retain_collection_types*
"""
attrs = fields(inst.__class__)
rv = dict_factory()
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,
dict_factory=dict_factory)
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain_collection_types is True else list
rv[a.name] = cf([
asdict(i, recurse=True, filter=filter,
dict_factory=dict_factory)
if has(i.__class__) else i
for i in v
])
elif isinstance(v, dict):
df = dict_factory
rv[a.name] = df((
asdict(kk, dict_factory=df) if has(kk.__class__) else kk,
asdict(vv, dict_factory=df) 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 astuple(inst, recurse=True, filter=None, tuple_factory=tuple,
retain_collection_types=False):
"""
Return the ``attrs`` attribute values of *inst* as a tuple.
Optionally recurse into other ``attrs``-decorated classes.
:param inst: Instance of an ``attrs``-decorated class.
:param bool recurse: Recurse into classes that are also
``attrs``-decorated.
:param callable filter: A callable whose return code determines 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.
:param callable tuple_factory: A callable to produce tuples from. For
example, to produce lists instead of tuples.
:param bool retain_collection_types: Do not convert to ``list``
or ``dict`` when encountering an attribute which type is
``tuple``, ``dict`` or ``set``. Only meaningful if ``recurse`` is
``True``.
:rtype: return type of *tuple_factory*
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 16.2.0
"""
attrs = fields(inst.__class__)
rv = []
retain = retain_collection_types # Very long. :/
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.append(astuple(v, recurse=True, filter=filter,
tuple_factory=tuple_factory,
retain_collection_types=retain))
elif isinstance(v, (tuple, list, set)):
cf = v.__class__ if retain is True else list
rv.append(cf([
astuple(j, recurse=True, filter=filter,
tuple_factory=tuple_factory,
retain_collection_types=retain)
if has(j.__class__) else j
for j in v
]))
elif isinstance(v, dict):
df = v.__class__ if retain is True else dict
rv.append(df(
(
astuple(
kk,
tuple_factory=tuple_factory,
retain_collection_types=retain
) if has(kk.__class__) else kk,
astuple(
vv,
tuple_factory=tuple_factory,
retain_collection_types=retain
) if has(vv.__class__) else vv
)
for kk, vv in iteritems(v)))
else:
rv.append(v)
else:
rv.append(v)
return rv if tuple_factory is list else tuple_factory(rv)
def has(cls):
"""
Check whether *cls* is a class with ``attrs`` attributes.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:rtype: :class:`bool`
"""
return getattr(cls, "__attrs_attrs__", None) is not None
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.
:raise attr.exceptions.AttrsAttributeNotFoundError: If *attr_name* couldn't
be found on *cls*.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. deprecated:: 17.1.0
Use :func:`evolve` instead.
"""
import warnings
warnings.warn("assoc is deprecated and will be removed after 2018/01.",
DeprecationWarning, stacklevel=2)
new = copy.copy(inst)
attrs = fields(inst.__class__)
for k, v in iteritems(changes):
a = getattr(attrs, k, NOTHING)
if a is NOTHING:
raise AttrsAttributeNotFoundError(
"{k} is not an attrs attribute on {cl}."
.format(k=k, cl=new.__class__)
)
_obj_setattr(new, k, v)
return new
def evolve(inst, **changes):
"""
Create a new instance, based on *inst* with *changes* applied.
: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.
:raise TypeError: If *attr_name* couldn't be found in the class
``__init__``.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
.. versionadded:: 17.1.0
"""
cls = inst.__class__
attrs = fields(cls)
for a in attrs:
if not a.init:
continue
attr_name = a.name # To deal with private attributes.
init_name = attr_name if attr_name[0] != "_" else attr_name[1:]
if init_name not in changes:
changes[init_name] = getattr(inst, attr_name)
return cls(**changes)

1689
third_party/python/attrs/src/attr/_make.py vendored Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,24 @@
"""
Commonly useful converters.
"""
from __future__ import absolute_import, division, print_function
def optional(converter):
"""
A converter that allows an attribute to be optional. An optional attribute
is one which can be set to ``None``.
:param callable converter: the converter that is used for non-``None``
values.
.. versionadded:: 17.1.0
"""
def optional_converter(val):
if val is None:
return None
return converter(val)
return optional_converter

View File

@ -0,0 +1,48 @@
from __future__ import absolute_import, division, print_function
class FrozenInstanceError(AttributeError):
"""
A frozen/immutable instance has been attempted to be modified.
It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing :exc:`AttributeError`.
.. versionadded:: 16.1.0
"""
msg = "can't set attribute"
args = [msg]
class AttrsAttributeNotFoundError(ValueError):
"""
An ``attrs`` function couldn't find an attribute that the user asked for.
.. versionadded:: 16.2.0
"""
class NotAnAttrsClassError(ValueError):
"""
A non-``attrs`` class has been passed into an ``attrs`` function.
.. versionadded:: 16.2.0
"""
class DefaultAlreadySetError(RuntimeError):
"""
A default has been set using ``attr.ib()`` and is attempted to be reset
using the decorator.
.. versionadded:: 17.1.0
"""
class UnannotatedAttributeError(RuntimeError):
"""
A class with ``auto_attribs=True`` has an ``attr.ib()`` without a type
annotation.
.. versionadded:: 17.3.0
"""

View File

@ -0,0 +1,52 @@
"""
Commonly useful filters for :func:`attr.asdict`.
"""
from __future__ import absolute_import, division, print_function
from ._compat import isclass
from ._make import Attribute
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isclass(cls)),
frozenset(cls for cls in what if isinstance(cls, 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_

View File

@ -0,0 +1,166 @@
"""
Commonly useful validators.
"""
from __future__ import absolute_import, division, print_function
from ._make import _AndValidator, and_, attrib, attrs
__all__ = [
"and_",
"in_",
"instance_of",
"optional",
"provides",
]
@attrs(repr=False, slots=True, hash=True)
class _InstanceOfValidator(object):
type = attrib()
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 (
"<instance_of validator for type {type!r}>"
.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 performed using
:func:`isinstance` therefore it's also valid to pass a tuple of types).
:param type: The type to check for.
:type type: type or tuple of types
:raises TypeError: With a human readable error message, the attribute
(of type :class:`attr.Attribute`), the expected type, and the value it
got.
"""
return _InstanceOfValidator(type)
@attrs(repr=False, slots=True, hash=True)
class _ProvidesValidator(object):
interface = attrib()
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 (
"<provides validator for interface {interface!r}>"
.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
<https://zopeinterface.readthedocs.io/en/latest/>`_).
:param zope.interface.Interface interface: The interface to check for.
:raises TypeError: With a human readable error message, the attribute
(of type :class:`attr.Attribute`), the expected interface, and the
value it got.
"""
return _ProvidesValidator(interface)
@attrs(repr=False, slots=True, hash=True)
class _OptionalValidator(object):
validator = attrib()
def __call__(self, inst, attr, value):
if value is None:
return
self.validator(inst, attr, value)
def __repr__(self):
return (
"<optional validator for {what} or None>"
.format(what=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 (or a list of validators) that is used for
non-``None`` values.
:type validator: callable or :class:`list` of callables.
.. versionadded:: 15.1.0
.. versionchanged:: 17.1.0 *validator* can be a list of validators.
"""
if isinstance(validator, list):
return _OptionalValidator(_AndValidator(validator))
return _OptionalValidator(validator)
@attrs(repr=False, slots=True, hash=True)
class _InValidator(object):
options = attrib()
def __call__(self, inst, attr, value):
if value not in self.options:
raise ValueError(
"'{name}' must be in {options!r} (got {value!r})"
.format(name=attr.name, options=self.options, value=value)
)
def __repr__(self):
return (
"<in_ validator with options {options!r}>"
.format(options=self.options)
)
def in_(options):
"""
A validator that raises a :exc:`ValueError` if the initializer is called
with a value that does not belong in the options provided. The check is
performed using ``value in options``.
:param options: Allowed options.
:type options: list, tuple, :class:`enum.Enum`, ...
:raises ValueError: With a human readable error message, the attribute (of
type :class:`attr.Attribute`), the expected options, and the value it
got.
.. versionadded:: 17.1.0
"""
return _InValidator(options)

View File

View File

@ -0,0 +1,203 @@
"""
Testing strategies for Hypothesis-based tests.
"""
import keyword
import string
from collections import OrderedDict
from hypothesis import strategies as st
import attr
from .utils import make_class
def gen_attr_names():
"""
Generate names for attributes, 'a'...'z', then 'aa'...'zz'.
~702 different attribute names should be enough in practice.
Some short strings (such as 'as') are keywords, so we skip them.
"""
lc = string.ascii_lowercase
for c in lc:
yield c
for outer in lc:
for inner in lc:
res = outer + inner
if keyword.iskeyword(res):
continue
yield outer + inner
def maybe_underscore_prefix(source):
"""
A generator to sometimes prepend an underscore.
"""
to_underscore = False
for val in source:
yield val if not to_underscore else '_' + val
to_underscore = not to_underscore
def _create_hyp_class(attrs):
"""
A helper function for Hypothesis to generate attrs classes.
"""
return make_class(
"HypClass", dict(zip(gen_attr_names(), attrs))
)
def _create_hyp_nested_strategy(simple_class_strategy):
"""
Create a recursive attrs class.
Given a strategy for building (simpler) classes, create and return
a strategy for building classes that have as an attribute: either just
the simpler class, a list of simpler classes, a tuple of simpler classes,
an ordered dict or a dict mapping the string "cls" to a simpler class.
"""
# Use a tuple strategy to combine simple attributes and an attr class.
def just_class(tup):
combined_attrs = list(tup[0])
combined_attrs.append(attr.ib(default=attr.Factory(tup[1])))
return _create_hyp_class(combined_attrs)
def list_of_class(tup):
default = attr.Factory(lambda: [tup[1]()])
combined_attrs = list(tup[0])
combined_attrs.append(attr.ib(default=default))
return _create_hyp_class(combined_attrs)
def tuple_of_class(tup):
default = attr.Factory(lambda: (tup[1](),))
combined_attrs = list(tup[0])
combined_attrs.append(attr.ib(default=default))
return _create_hyp_class(combined_attrs)
def dict_of_class(tup):
default = attr.Factory(lambda: {"cls": tup[1]()})
combined_attrs = list(tup[0])
combined_attrs.append(attr.ib(default=default))
return _create_hyp_class(combined_attrs)
def ordereddict_of_class(tup):
default = attr.Factory(lambda: OrderedDict([("cls", tup[1]())]))
combined_attrs = list(tup[0])
combined_attrs.append(attr.ib(default=default))
return _create_hyp_class(combined_attrs)
# A strategy producing tuples of the form ([list of attributes], <given
# class strategy>).
attrs_and_classes = st.tuples(list_of_attrs, simple_class_strategy)
return st.one_of(attrs_and_classes.map(just_class),
attrs_and_classes.map(list_of_class),
attrs_and_classes.map(tuple_of_class),
attrs_and_classes.map(dict_of_class),
attrs_and_classes.map(ordereddict_of_class))
bare_attrs = st.builds(attr.ib, default=st.none())
int_attrs = st.integers().map(lambda i: attr.ib(default=i))
str_attrs = st.text().map(lambda s: attr.ib(default=s))
float_attrs = st.floats().map(lambda f: attr.ib(default=f))
dict_attrs = (st.dictionaries(keys=st.text(), values=st.integers())
.map(lambda d: attr.ib(default=d)))
simple_attrs_without_metadata = (bare_attrs | int_attrs | str_attrs |
float_attrs | dict_attrs)
@st.composite
def simple_attrs_with_metadata(draw):
"""
Create a simple attribute with arbitrary metadata.
"""
c_attr = draw(simple_attrs)
keys = st.booleans() | st.binary() | st.integers() | st.text()
vals = st.booleans() | st.binary() | st.integers() | st.text()
metadata = draw(st.dictionaries(
keys=keys, values=vals, min_size=1, max_size=5))
return attr.ib(
default=c_attr._default,
validator=c_attr._validator,
repr=c_attr.repr,
cmp=c_attr.cmp,
hash=c_attr.hash,
init=c_attr.init,
metadata=metadata,
type=None,
converter=c_attr.converter,
)
simple_attrs = simple_attrs_without_metadata | simple_attrs_with_metadata()
# Python functions support up to 255 arguments.
list_of_attrs = st.lists(simple_attrs, max_size=9)
@st.composite
def simple_classes(draw, slots=None, frozen=None, private_attrs=None):
"""
A strategy that generates classes with default non-attr attributes.
For example, this strategy might generate a class such as:
@attr.s(slots=True, frozen=True)
class HypClass:
a = attr.ib(default=1)
_b = attr.ib(default=None)
c = attr.ib(default='text')
_d = attr.ib(default=1.0)
c = attr.ib(default={'t': 1})
By default, all combinations of slots and frozen classes will be generated.
If `slots=True` is passed in, only slots classes will be generated, and
if `slots=False` is passed in, no slot classes will be generated. The same
applies to `frozen`.
By default, some attributes will be private (i.e. prefixed with an
underscore). If `private_attrs=True` is passed in, all attributes will be
private, and if `private_attrs=False`, no attributes will be private.
"""
attrs = draw(list_of_attrs)
frozen_flag = draw(st.booleans()) if frozen is None else frozen
slots_flag = draw(st.booleans()) if slots is None else slots
if private_attrs is None:
attr_names = maybe_underscore_prefix(gen_attr_names())
elif private_attrs is True:
attr_names = ('_' + n for n in gen_attr_names())
elif private_attrs is False:
attr_names = gen_attr_names()
cls_dict = dict(zip(attr_names, attrs))
post_init_flag = draw(st.booleans())
if post_init_flag:
def post_init(self):
pass
cls_dict["__attrs_post_init__"] = post_init
return make_class(
"HypClass",
cls_dict,
slots=slots_flag,
frozen=frozen_flag,
)
# st.recursive works by taking a base strategy (in this case, simple_classes)
# and a special function. This function receives a strategy, and returns
# another strategy (building on top of the base strategy).
nested_classes = st.recursive(
simple_classes(),
_create_hyp_nested_strategy,
max_leaves=10
)

View File

@ -0,0 +1,229 @@
"""
Tests for PEP-526 type annotations.
Python 3.6+ only.
"""
import types
import typing
import pytest
import attr
from attr._make import _classvar_prefixes
from attr.exceptions import UnannotatedAttributeError
class TestAnnotations:
"""
Tests for types derived from variable annotations (PEP-526).
"""
def test_basic_annotations(self):
"""
Sets the `Attribute.type` attr from basic type annotations.
"""
@attr.s
class C:
x: int = attr.ib()
y = attr.ib(type=str)
z = attr.ib()
assert int is attr.fields(C).x.type
assert str is attr.fields(C).y.type
assert None is attr.fields(C).z.type
assert C.__init__.__annotations__ == {
'x': int,
'y': str,
'return': None,
}
def test_catches_basic_type_conflict(self):
"""
Raises ValueError if type is specified both ways.
"""
with pytest.raises(ValueError) as e:
@attr.s
class C:
x: int = attr.ib(type=int)
assert (
"Type annotation and type argument cannot both be present",
) == e.value.args
def test_typing_annotations(self):
"""
Sets the `Attribute.type` attr from typing annotations.
"""
@attr.s
class C:
x: typing.List[int] = attr.ib()
y = attr.ib(type=typing.Optional[str])
assert typing.List[int] is attr.fields(C).x.type
assert typing.Optional[str] is attr.fields(C).y.type
assert C.__init__.__annotations__ == {
'x': typing.List[int],
'y': typing.Optional[str],
'return': None,
}
def test_only_attrs_annotations_collected(self):
"""
Annotations that aren't set to an attr.ib are ignored.
"""
@attr.s
class C:
x: typing.List[int] = attr.ib()
y: int
assert 1 == len(attr.fields(C))
assert C.__init__.__annotations__ == {
'x': typing.List[int],
'return': None,
}
@pytest.mark.parametrize("slots", [True, False])
def test_auto_attribs(self, slots):
"""
If *auto_attribs* is True, bare annotations are collected too.
Defaults work and class variables are ignored.
"""
@attr.s(auto_attribs=True, slots=slots)
class C:
cls_var: typing.ClassVar[int] = 23
a: int
x: typing.List[int] = attr.Factory(list)
y: int = 2
z: int = attr.ib(default=3)
foo: typing.Any = None
i = C(42)
assert "C(a=42, x=[], y=2, z=3, foo=None)" == repr(i)
attr_names = set(a.name for a in C.__attrs_attrs__)
assert "a" in attr_names # just double check that the set works
assert "cls_var" not in attr_names
assert int == attr.fields(C).a.type
assert attr.Factory(list) == attr.fields(C).x.default
assert typing.List[int] == attr.fields(C).x.type
assert int == attr.fields(C).y.type
assert 2 == attr.fields(C).y.default
assert int == attr.fields(C).z.type
assert typing.Any == attr.fields(C).foo.type
# Class body is clean.
if slots is False:
with pytest.raises(AttributeError):
C.y
assert 2 == i.y
else:
assert isinstance(C.y, types.MemberDescriptorType)
i.y = 23
assert 23 == i.y
assert C.__init__.__annotations__ == {
'a': int,
'x': typing.List[int],
'y': int,
'z': int,
'foo': typing.Any,
'return': None,
}
@pytest.mark.parametrize("slots", [True, False])
def test_auto_attribs_unannotated(self, slots):
"""
Unannotated `attr.ib`s raise an error.
"""
with pytest.raises(UnannotatedAttributeError) as e:
@attr.s(slots=slots, auto_attribs=True)
class C:
v = attr.ib()
x: int
y = attr.ib()
z: str
assert (
"The following `attr.ib`s lack a type annotation: v, y.",
) == e.value.args
@pytest.mark.parametrize("slots", [True, False])
def test_auto_attribs_subclassing(self, slots):
"""
Attributes from super classes are inherited, it doesn't matter if the
subclass has annotations or not.
Ref #291
"""
@attr.s(slots=slots, auto_attribs=True)
class A:
a: int = 1
@attr.s(slots=slots, auto_attribs=True)
class B(A):
b: int = 2
@attr.s(slots=slots, auto_attribs=True)
class C(A):
pass
assert "B(a=1, b=2)" == repr(B())
assert "C(a=1)" == repr(C())
assert A.__init__.__annotations__ == {
'a': int,
'return': None,
}
assert B.__init__.__annotations__ == {
'a': int,
'b': int,
'return': None,
}
assert C.__init__.__annotations__ == {
'a': int,
'return': None,
}
def test_converter_annotations(self):
"""
Attributes with converters don't have annotations.
"""
@attr.s(auto_attribs=True)
class A:
a: int = attr.ib(converter=int)
assert A.__init__.__annotations__ == {'return': None}
@pytest.mark.parametrize("slots", [True, False])
@pytest.mark.parametrize("classvar", _classvar_prefixes)
def test_annotations_strings(self, slots, classvar):
"""
String annotations are passed into __init__ as is.
"""
@attr.s(auto_attribs=True, slots=slots)
class C:
cls_var: classvar + '[int]' = 23
a: 'int'
x: 'typing.List[int]' = attr.Factory(list)
y: 'int' = 2
z: 'int' = attr.ib(default=3)
foo: 'typing.Any' = None
assert C.__init__.__annotations__ == {
'a': 'int',
'x': 'typing.List[int]',
'y': 'int',
'z': 'int',
'foo': 'typing.Any',
'return': None,
}

View File

@ -0,0 +1,43 @@
"""
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]

View File

@ -0,0 +1,36 @@
"""
Tests for `attr.converters`.
"""
from __future__ import absolute_import
import pytest
from attr.converters import optional
class TestOptional(object):
"""
Tests for `optional`.
"""
def test_success_with_type(self):
"""
Wrapped converter is used as usual if value is not None.
"""
c = optional(int)
assert c("42") == 42
def test_success_with_none(self):
"""
Nothing happens if None.
"""
c = optional(int)
assert c(None) is None
def test_fail(self):
"""
Propagates the underlying conversion error when conversion fails.
"""
c = optional(int)
with pytest.raises(ValueError):
c("not_an_int")

View File

@ -0,0 +1,415 @@
"""
End-to-end tests.
"""
from __future__ import absolute_import, division, print_function
import pickle
import pytest
import six
from hypothesis import given
from hypothesis.strategies import booleans
import attr
from attr._compat import TYPE
from attr._make import NOTHING, Attribute
from attr.exceptions import FrozenInstanceError
@attr.s
class C1(object):
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
@attr.s(slots=True)
class C1Slots(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(slots=True)
class C2Slots(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(slots=True)
class SuperSlots(object):
x = attr.ib()
def meth(self):
return self.x
@attr.s
class Sub(Super):
y = attr.ib()
@attr.s(slots=True)
class SubSlots(SuperSlots):
y = attr.ib()
@attr.s(frozen=True, slots=True)
class Frozen(object):
x = attr.ib()
@attr.s
class SubFrozen(Frozen):
y = attr.ib()
@attr.s(frozen=True, slots=False)
class FrozenNoSlots(object):
x = attr.ib()
class Meta(type):
pass
@attr.s
@six.add_metaclass(Meta)
class WithMeta(object):
pass
@attr.s(slots=True)
@six.add_metaclass(Meta)
class WithMetaSlots(object):
pass
FromMakeClass = attr.make_class("FromMakeClass", ["x"])
class TestDarkMagic(object):
"""
Integration tests.
"""
@pytest.mark.parametrize("cls", [C2, C2Slots])
def test_fields(self, cls):
"""
`attr.fields` works.
"""
assert (
Attribute(name="x", default=foo, validator=None,
repr=True, cmp=True, hash=None, init=True),
Attribute(name="y", default=attr.Factory(list), validator=None,
repr=True, cmp=True, hash=None, init=True),
) == attr.fields(cls)
@pytest.mark.parametrize("cls", [C1, C1Slots])
def test_asdict(self, cls):
"""
`attr.asdict` works.
"""
assert {
"x": 1,
"y": 2,
} == attr.asdict(cls(x=1, y=2))
@pytest.mark.parametrize("cls", [C1, C1Slots])
def test_validator(self, cls):
"""
`instance_of` raises `TypeError` on type mismatch.
"""
with pytest.raises(TypeError) as e:
cls("1", 2)
# Using C1 explicitly, since slot classes don't support this.
assert (
"'x' must be <{type} 'int'> (got '1' that is a <{type} "
"'str'>).".format(type=TYPE),
attr.fields(C1).x, int, "1",
) == e.value.args
@given(booleans())
def test_renaming(self, slots):
"""
Private members are renamed but only in `__init__`.
"""
@attr.s(slots=slots)
class C3(object):
_x = attr.ib()
assert "C3(_x=1)" == repr(C3(x=1))
@given(booleans(), booleans())
def test_programmatic(self, slots, frozen):
"""
`attr.make_class` works.
"""
PC = attr.make_class("PC", ["a", "b"], slots=slots, frozen=frozen)
assert (
Attribute(name="a", default=NOTHING, validator=None,
repr=True, cmp=True, hash=None, init=True),
Attribute(name="b", default=NOTHING, validator=None,
repr=True, cmp=True, hash=None, init=True),
) == attr.fields(PC)
@pytest.mark.parametrize("cls", [Sub, SubSlots])
def test_subclassing_with_extra_attrs(self, cls):
"""
Sub-classing (where the subclass has extra attrs) does what you'd hope
for.
"""
obj = object()
i = cls(x=obj, y=2)
assert i.x is i.meth() is obj
assert i.y == 2
if cls is Sub:
assert "Sub(x={obj}, y=2)".format(obj=obj) == repr(i)
else:
assert "SubSlots(x={obj}, y=2)".format(obj=obj) == repr(i)
@pytest.mark.parametrize("base", [Super, SuperSlots])
def test_subclass_without_extra_attrs(self, base):
"""
Sub-classing (where the subclass does not have extra attrs) still
behaves the same as a subclass with extra attrs.
"""
class Sub2(base):
pass
obj = object()
i = Sub2(x=obj)
assert i.x is i.meth() is obj
assert "Sub2(x={obj})".format(obj=obj) == repr(i)
@pytest.mark.parametrize("frozen_class", [
Frozen, # has slots=True
attr.make_class("FrozenToo", ["x"], slots=False, frozen=True),
])
def test_frozen_instance(self, frozen_class):
"""
Frozen instances can't be modified (easily).
"""
frozen = frozen_class(1)
with pytest.raises(FrozenInstanceError) as e:
frozen.x = 2
with pytest.raises(FrozenInstanceError) as e:
del frozen.x
assert e.value.args[0] == "can't set attribute"
assert 1 == frozen.x
@pytest.mark.parametrize("cls",
[C1, C1Slots, C2, C2Slots, Super, SuperSlots,
Sub, SubSlots, Frozen, FrozenNoSlots,
FromMakeClass])
@pytest.mark.parametrize("protocol",
range(2, pickle.HIGHEST_PROTOCOL + 1))
def test_pickle_attributes(self, cls, protocol):
"""
Pickling/un-pickling of Attribute instances works.
"""
for attribute in attr.fields(cls):
assert attribute == pickle.loads(pickle.dumps(attribute, protocol))
@pytest.mark.parametrize("cls",
[C1, C1Slots, C2, C2Slots, Super, SuperSlots,
Sub, SubSlots, Frozen, FrozenNoSlots,
FromMakeClass])
@pytest.mark.parametrize("protocol",
range(2, pickle.HIGHEST_PROTOCOL + 1))
def test_pickle_object(self, cls, protocol):
"""
Pickle object serialization works on all kinds of attrs classes.
"""
if len(attr.fields(cls)) == 2:
obj = cls(123, 456)
else:
obj = cls(123)
assert repr(obj) == repr(pickle.loads(pickle.dumps(obj, protocol)))
def test_subclassing_frozen_gives_frozen(self):
"""
The frozen-ness of classes is inherited. Subclasses of frozen classes
are also frozen and can be instantiated.
"""
i = SubFrozen("foo", "bar")
assert i.x == "foo"
assert i.y == "bar"
@pytest.mark.parametrize("cls", [WithMeta, WithMetaSlots])
def test_metaclass_preserved(self, cls):
"""
Metaclass data is preserved.
"""
assert Meta == type(cls)
def test_default_decorator(self):
"""
Default decorator sets the default and the respective method gets
called.
"""
@attr.s
class C(object):
x = attr.ib(default=1)
y = attr.ib()
@y.default
def compute(self):
return self.x + 1
assert C(1, 2) == C()
@pytest.mark.parametrize("slots", [True, False])
@pytest.mark.parametrize("frozen", [True, False])
def test_attrib_overwrite(self, slots, frozen):
"""
Subclasses can overwrite attributes of their superclass.
"""
@attr.s(slots=slots, frozen=frozen)
class SubOverwrite(Super):
x = attr.ib(default=attr.Factory(list))
assert SubOverwrite([]) == SubOverwrite()
def test_dict_patch_class(self):
"""
dict-classes are never replaced.
"""
class C(object):
x = attr.ib()
C_new = attr.s(C)
assert C_new is C
def test_hash_by_id(self):
"""
With dict classes, hashing by ID is active for hash=False even on
Python 3. This is incorrect behavior but we have to retain it for
backward compatibility.
"""
@attr.s(hash=False)
class HashByIDBackwardCompat(object):
x = attr.ib()
assert (
hash(HashByIDBackwardCompat(1)) != hash(HashByIDBackwardCompat(1))
)
@attr.s(hash=False, cmp=False)
class HashByID(object):
x = attr.ib()
assert hash(HashByID(1)) != hash(HashByID(1))
@attr.s(hash=True)
class HashByValues(object):
x = attr.ib()
assert hash(HashByValues(1)) == hash(HashByValues(1))
def test_handles_different_defaults(self):
"""
Unhashable defaults + subclassing values work.
"""
@attr.s
class Unhashable(object):
pass
@attr.s
class C(object):
x = attr.ib(default=Unhashable())
@attr.s
class D(C):
pass
@pytest.mark.parametrize("slots", [True, False])
def test_hash_false_cmp_false(self, slots):
"""
hash=False and cmp=False make a class hashable by ID.
"""
@attr.s(hash=False, cmp=False, slots=slots)
class C(object):
pass
assert hash(C()) != hash(C())
def test_overwrite_super(self):
"""
Super classes can overwrite each other and the attributes are added
in the order they are defined.
"""
@attr.s
class C(object):
c = attr.ib(default=100)
x = attr.ib(default=1)
b = attr.ib(default=23)
@attr.s
class D(C):
a = attr.ib(default=42)
x = attr.ib(default=2)
d = attr.ib(default=3.14)
@attr.s
class E(D):
y = attr.ib(default=3)
z = attr.ib(default=4)
assert "E(c=100, b=23, a=42, x=2, d=3.14, y=3, z=4)" == repr(E())
@pytest.mark.parametrize("base_slots", [True, False])
@pytest.mark.parametrize("sub_slots", [True, False])
@pytest.mark.parametrize("base_frozen", [True, False])
@pytest.mark.parametrize("sub_frozen", [True, False])
@pytest.mark.parametrize("base_converter", [True, False])
@pytest.mark.parametrize("sub_converter", [True, False])
def test_frozen_slots_combo(self, base_slots, sub_slots, base_frozen,
sub_frozen, base_converter, sub_converter):
"""
A class with a single attribute, inheriting from another class
with a single attribute.
"""
@attr.s(frozen=base_frozen, slots=base_slots)
class Base(object):
a = attr.ib(converter=int if base_converter else None)
@attr.s(frozen=sub_frozen, slots=sub_slots)
class Sub(Base):
b = attr.ib(converter=int if sub_converter else None)
i = Sub("1", "2")
assert i.a == (1 if base_converter else "1")
assert i.b == (2 if sub_converter else "2")
if base_frozen or sub_frozen:
with pytest.raises(FrozenInstanceError):
i.a = "2"
with pytest.raises(FrozenInstanceError):
i.b = "3"

View File

@ -0,0 +1,526 @@
"""
Tests for dunder methods from `attrib._make`.
"""
from __future__ import absolute_import, division, print_function
import copy
import pytest
from hypothesis import given
from hypothesis.strategies import booleans
import attr
from attr._make import (
NOTHING, Factory, _add_init, _add_repr, _Nothing, fields, make_class
)
from attr.validators import instance_of
from .utils import simple_attr, simple_class
CmpC = simple_class(cmp=True)
CmpCSlots = simple_class(cmp=True, slots=True)
ReprC = simple_class(repr=True)
ReprCSlots = simple_class(repr=True, slots=True)
# HashC is hashable by explicit definition while HashCSlots is hashable
# implicitly.
HashC = simple_class(hash=True)
HashCSlots = simple_class(hash=None, cmp=True, frozen=True, slots=True)
class InitC(object):
__attrs_attrs__ = [simple_attr("a"), simple_attr("b")]
InitC = _add_init(InitC, False)
class TestAddCmp(object):
"""
Tests for `_add_cmp`.
"""
@given(booleans())
def test_cmp(self, slots):
"""
If `cmp` is False, ignore that attribute.
"""
C = make_class("C", {
"a": attr.ib(cmp=False),
"b": attr.ib()
}, slots=slots)
assert C(1, 2) == C(2, 2)
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_equal(self, cls):
"""
Equal objects are detected as equal.
"""
assert cls(1, 2) == cls(1, 2)
assert not (cls(1, 2) != cls(1, 2))
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_unequal_same_class(self, cls):
"""
Unequal objects of correct type are detected as unequal.
"""
assert cls(1, 2) != cls(2, 1)
assert not (cls(1, 2) == cls(2, 1))
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_unequal_different_class(self, cls):
"""
Unequal objects of different type are detected even if their attributes
match.
"""
class NotCmpC(object):
a = 1
b = 2
assert cls(1, 2) != NotCmpC()
assert not (cls(1, 2) == NotCmpC())
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_lt(self, cls):
"""
__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 cls(*a) < cls(*b)
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_lt_unordable(self, cls):
"""
__lt__ returns NotImplemented if classes differ.
"""
assert NotImplemented == (cls(1, 2).__lt__(42))
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_le(self, cls):
"""
__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 cls(*a) <= cls(*b)
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_le_unordable(self, cls):
"""
__le__ returns NotImplemented if classes differ.
"""
assert NotImplemented == (cls(1, 2).__le__(42))
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_gt(self, cls):
"""
__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 cls(*a) > cls(*b)
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_gt_unordable(self, cls):
"""
__gt__ returns NotImplemented if classes differ.
"""
assert NotImplemented == (cls(1, 2).__gt__(42))
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_ge(self, cls):
"""
__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 cls(*a) >= cls(*b)
@pytest.mark.parametrize("cls", [CmpC, CmpCSlots])
def test_ge_unordable(self, cls):
"""
__ge__ returns NotImplemented if classes differ.
"""
assert NotImplemented == (cls(1, 2).__ge__(42))
class TestAddRepr(object):
"""
Tests for `_add_repr`.
"""
@pytest.mark.parametrize("slots", [True, False])
def test_repr(self, slots):
"""
If `repr` is False, ignore that attribute.
"""
C = make_class("C", {
"a": attr.ib(repr=False),
"b": attr.ib()
}, slots=slots)
assert "C(b=2)" == repr(C(1, 2))
@pytest.mark.parametrize("cls", [ReprC, ReprCSlots])
def test_repr_works(self, cls):
"""
repr returns a sensible value.
"""
assert "C(a=1, b=2)" == repr(cls(1, 2))
def test_infinite_recursion(self):
"""
In the presence of a cyclic graph, repr will emit an ellipsis and not
raise an exception.
"""
@attr.s
class Cycle(object):
value = attr.ib(default=7)
cycle = attr.ib(default=None)
cycle = Cycle()
cycle.cycle = cycle
assert "Cycle(value=7, cycle=...)" == repr(cycle)
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)
def test_repr_uninitialized_member(self):
"""
repr signals unset attributes
"""
C = make_class("C", {
"a": attr.ib(init=False),
})
assert "C(a=NOTHING)" == repr(C())
@given(add_str=booleans(), slots=booleans())
def test_str(self, add_str, slots):
"""
If str is True, it returns the same as repr.
This only makes sense when subclassing a class with an poor __str__
(like Exceptions).
"""
@attr.s(str=add_str, slots=slots)
class Error(Exception):
x = attr.ib()
e = Error(42)
assert (str(e) == repr(e)) is add_str
def test_str_no_repr(self):
"""
Raises a ValueError if repr=False and str=True.
"""
with pytest.raises(ValueError) as e:
simple_class(repr=False, str=True)
assert (
"__str__ can only be generated if a __repr__ exists."
) == e.value.args[0]
class TestAddHash(object):
"""
Tests for `_add_hash`.
"""
def test_enforces_type(self):
"""
The `hash` argument to both attrs and attrib must be None, True, or
False.
"""
exc_args = ("Invalid value for hash. Must be True, False, or None.",)
with pytest.raises(TypeError) as e:
make_class("C", {}, hash=1),
assert exc_args == e.value.args
with pytest.raises(TypeError) as e:
make_class("C", {"a": attr.ib(hash=1)}),
assert exc_args == e.value.args
@given(booleans())
def test_hash_attribute(self, slots):
"""
If `hash` is False on an attribute, ignore that attribute.
"""
C = make_class("C", {"a": attr.ib(hash=False), "b": attr.ib()},
slots=slots, hash=True)
assert hash(C(1, 2)) == hash(C(2, 2))
@given(booleans())
def test_hash_attribute_mirrors_cmp(self, cmp):
"""
If `hash` is None, the hash generation mirrors `cmp`.
"""
C = make_class("C", {"a": attr.ib(cmp=cmp)}, cmp=True, frozen=True)
if cmp:
assert C(1) != C(2)
assert hash(C(1)) != hash(C(2))
assert hash(C(1)) == hash(C(1))
else:
assert C(1) == C(2)
assert hash(C(1)) == hash(C(2))
@given(booleans())
def test_hash_mirrors_cmp(self, cmp):
"""
If `hash` is None, the hash generation mirrors `cmp`.
"""
C = make_class("C", {"a": attr.ib()}, cmp=cmp, frozen=True)
i = C(1)
assert i == i
assert hash(i) == hash(i)
if cmp:
assert C(1) == C(1)
assert hash(C(1)) == hash(C(1))
else:
assert C(1) != C(1)
assert hash(C(1)) != hash(C(1))
@pytest.mark.parametrize("cls", [HashC, HashCSlots])
def test_hash_works(self, cls):
"""
__hash__ returns different hashes for different values.
"""
assert hash(cls(1, 2)) != hash(cls(1, 1))
def test_hash_default(self):
"""
Classes are not hashable by default.
"""
C = make_class("C", {})
with pytest.raises(TypeError) as e:
hash(C())
assert e.value.args[0] in (
"'C' objects are unhashable", # PyPy
"unhashable type: 'C'", # CPython
)
class TestAddInit(object):
"""
Tests for `_add_init`.
"""
@given(booleans(), booleans())
def test_init(self, slots, frozen):
"""
If `init` is False, ignore that attribute.
"""
C = make_class("C", {"a": attr.ib(init=False), "b": attr.ib()},
slots=slots, frozen=frozen)
with pytest.raises(TypeError) as e:
C(a=1, b=2)
assert (
"__init__() got an unexpected keyword argument 'a'" ==
e.value.args[0]
)
@given(booleans(), booleans())
def test_no_init_default(self, slots, frozen):
"""
If `init` is False but a Factory is specified, don't allow passing that
argument but initialize it anyway.
"""
C = make_class("C", {
"_a": attr.ib(init=False, default=42),
"_b": attr.ib(init=False, default=Factory(list)),
"c": attr.ib()
}, slots=slots, frozen=frozen)
with pytest.raises(TypeError):
C(a=1, c=2)
with pytest.raises(TypeError):
C(b=1, c=2)
i = C(23)
assert (42, [], 23) == (i._a, i._b, i.c)
@given(booleans(), booleans())
def test_no_init_order(self, slots, frozen):
"""
If an attribute is `init=False`, it's legal to come after a mandatory
attribute.
"""
make_class("C", {
"a": attr.ib(default=Factory(list)),
"b": attr.ib(init=False),
}, slots=slots, frozen=frozen)
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, False)
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, False)
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.ib("a", validator=raiser)})
with pytest.raises(VException) as e:
C(42)
assert (fields(C).a, 42,) == e.value.args[1:]
assert isinstance(e.value.args[0], C)
def test_validator_slots(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.ib("a", validator=raiser)}, slots=True)
with pytest.raises(VException) as e:
C(42)
assert (fields(C)[0], 42,) == e.value.args[1:]
assert isinstance(e.value.args[0], C)
@given(booleans())
def test_validator_others(self, slots):
"""
Does not interfere when setting non-attrs attributes.
"""
C = make_class("C", {
"a": attr.ib("a", validator=instance_of(int))
}, slots=slots)
i = C(1)
assert 1 == i.a
if not slots:
i.b = "foo"
assert "foo" == i.b
else:
with pytest.raises(AttributeError):
i.b = "foo"
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, False)
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())
assert 1 != _Nothing()

View File

@ -0,0 +1,94 @@
"""
Tests for `attr.filters`.
"""
from __future__ import absolute_import, division, print_function
import pytest
import attr
from attr import fields
from attr.filters import _split_what, exclude, include
@attr.s
class C(object):
a = attr.ib()
b = attr.ib()
class TestSplitWhat(object):
"""
Tests for `_split_what`.
"""
def test_splits(self):
"""
Splits correctly.
"""
assert (
frozenset((int, str)),
frozenset((fields(C).a,)),
) == _split_what((str, fields(C).a, int,))
class TestInclude(object):
"""
Tests for `include`.
"""
@pytest.mark.parametrize("incl,value", [
((int,), 42),
((str,), "hello"),
((str, fields(C).a), 42),
((str, fields(C).b), "hello"),
])
def test_allow(self, incl, value):
"""
Return True if a class or attribute is whitelisted.
"""
i = include(*incl)
assert i(fields(C).a, value) is True
@pytest.mark.parametrize("incl,value", [
((str,), 42),
((int,), "hello"),
((str, fields(C).b), 42),
((int, fields(C).b), "hello"),
])
def test_drop_class(self, incl, value):
"""
Return False on non-whitelisted classes and attributes.
"""
i = include(*incl)
assert i(fields(C).a, value) is False
class TestExclude(object):
"""
Tests for `exclude`.
"""
@pytest.mark.parametrize("excl,value", [
((str,), 42),
((int,), "hello"),
((str, fields(C).b), 42),
((int, fields(C).b), "hello"),
])
def test_allow(self, excl, value):
"""
Return True if class or attribute is not blacklisted.
"""
e = exclude(*excl)
assert e(fields(C).a, value) is True
@pytest.mark.parametrize("excl,value", [
((int,), 42),
((str,), "hello"),
((str, fields(C).a), 42),
((str, fields(C).b), "hello"),
])
def test_drop_class(self, excl, value):
"""
Return True on non-blacklisted classes and attributes.
"""
e = exclude(*excl)
assert e(fields(C).a, value) is False

View File

@ -0,0 +1,527 @@
"""
Tests for `attr._funcs`.
"""
from __future__ import absolute_import, division, print_function
from collections import Mapping, OrderedDict, Sequence
import pytest
from hypothesis import HealthCheck, assume, given, settings
from hypothesis import strategies as st
import attr
from attr import asdict, assoc, astuple, evolve, fields, has
from attr._compat import TYPE
from attr.exceptions import AttrsAttributeNotFoundError
from attr.validators import instance_of
from .strategies import nested_classes, simple_classes
MAPPING_TYPES = (dict, OrderedDict)
SEQUENCE_TYPES = (list, tuple)
class TestAsDict(object):
"""
Tests for `asdict`.
"""
@given(st.sampled_from(MAPPING_TYPES))
def test_shallow(self, C, dict_factory):
"""
Shallow asdict returns correct dict.
"""
assert {
"x": 1,
"y": 2,
} == asdict(C(x=1, y=2), False, dict_factory=dict_factory)
@given(st.sampled_from(MAPPING_TYPES))
def test_recurse(self, C, dict_class):
"""
Deep asdict returns correct dict.
"""
assert {
"x": {"x": 1, "y": 2},
"y": {"x": 3, "y": 4},
} == asdict(C(
C(1, 2),
C(3, 4),
), dict_factory=dict_class)
@given(nested_classes, st.sampled_from(MAPPING_TYPES))
@settings(suppress_health_check=[HealthCheck.too_slow])
def test_recurse_property(self, cls, dict_class):
"""
Property tests for recursive asdict.
"""
obj = cls()
obj_dict = asdict(obj, dict_factory=dict_class)
def assert_proper_dict_class(obj, obj_dict):
assert isinstance(obj_dict, dict_class)
for field in fields(obj.__class__):
field_val = getattr(obj, field.name)
if has(field_val.__class__):
# This field holds a class, recurse the assertions.
assert_proper_dict_class(field_val, obj_dict[field.name])
elif isinstance(field_val, Sequence):
dict_val = obj_dict[field.name]
for item, item_dict in zip(field_val, dict_val):
if has(item.__class__):
assert_proper_dict_class(item, item_dict)
elif isinstance(field_val, Mapping):
# This field holds a dictionary.
assert isinstance(obj_dict[field.name], dict_class)
for key, val in field_val.items():
if has(val.__class__):
assert_proper_dict_class(val,
obj_dict[field.name][key])
assert_proper_dict_class(obj, obj_dict)
@given(st.sampled_from(MAPPING_TYPES))
def test_filter(self, C, dict_factory):
"""
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", dict_factory=dict_factory)
@given(container=st.sampled_from(SEQUENCE_TYPES))
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"])))
@given(container=st.sampled_from(SEQUENCE_TYPES))
def test_lists_tuples_retain_type(self, container, C):
"""
If recurse and retain_collection_types are True, also recurse
into lists and do not convert them into list.
"""
assert {
"x": 1,
"y": container([{"x": 2, "y": 3}, {"x": 4, "y": 5}, "a"]),
} == asdict(C(1, container([C(2, 3), C(4, 5), "a"])),
retain_collection_types=True)
@given(st.sampled_from(MAPPING_TYPES))
def test_dicts(self, C, dict_factory):
"""
If recurse is True, also recurse into dicts.
"""
res = asdict(C(1, {"a": C(4, 5)}), dict_factory=dict_factory)
assert {
"x": 1,
"y": {"a": {"x": 4, "y": 5}},
} == res
assert isinstance(res, dict_factory)
@given(simple_classes(private_attrs=False), st.sampled_from(MAPPING_TYPES))
def test_roundtrip(self, cls, dict_class):
"""
Test dumping to dicts and back for Hypothesis-generated classes.
Private attributes don't round-trip (the attribute name is different
than the initializer argument).
"""
instance = cls()
dict_instance = asdict(instance, dict_factory=dict_class)
assert isinstance(dict_instance, dict_class)
roundtrip_instance = cls(**dict_instance)
assert instance == roundtrip_instance
@given(simple_classes())
def test_asdict_preserve_order(self, cls):
"""
Field order should be preserved when dumping to OrderedDicts.
"""
instance = cls()
dict_instance = asdict(instance, dict_factory=OrderedDict)
assert [a.name for a in fields(cls)] == list(dict_instance.keys())
class TestAsTuple(object):
"""
Tests for `astuple`.
"""
@given(st.sampled_from(SEQUENCE_TYPES))
def test_shallow(self, C, tuple_factory):
"""
Shallow astuple returns correct dict.
"""
assert (tuple_factory([1, 2]) ==
astuple(C(x=1, y=2), False, tuple_factory=tuple_factory))
@given(st.sampled_from(SEQUENCE_TYPES))
def test_recurse(self, C, tuple_factory):
"""
Deep astuple returns correct tuple.
"""
assert (tuple_factory([tuple_factory([1, 2]),
tuple_factory([3, 4])])
== astuple(C(
C(1, 2),
C(3, 4),
),
tuple_factory=tuple_factory))
@given(nested_classes, st.sampled_from(SEQUENCE_TYPES))
@settings(suppress_health_check=[HealthCheck.too_slow])
def test_recurse_property(self, cls, tuple_class):
"""
Property tests for recursive astuple.
"""
obj = cls()
obj_tuple = astuple(obj, tuple_factory=tuple_class)
def assert_proper_tuple_class(obj, obj_tuple):
assert isinstance(obj_tuple, tuple_class)
for index, field in enumerate(fields(obj.__class__)):
field_val = getattr(obj, field.name)
if has(field_val.__class__):
# This field holds a class, recurse the assertions.
assert_proper_tuple_class(field_val, obj_tuple[index])
assert_proper_tuple_class(obj, obj_tuple)
@given(nested_classes, st.sampled_from(SEQUENCE_TYPES))
@settings(suppress_health_check=[HealthCheck.too_slow])
def test_recurse_retain(self, cls, tuple_class):
"""
Property tests for asserting collection types are retained.
"""
obj = cls()
obj_tuple = astuple(obj, tuple_factory=tuple_class,
retain_collection_types=True)
def assert_proper_col_class(obj, obj_tuple):
# Iterate over all attributes, and if they are lists or mappings
# in the original, assert they are the same class in the dumped.
for index, field in enumerate(fields(obj.__class__)):
field_val = getattr(obj, field.name)
if has(field_val.__class__):
# This field holds a class, recurse the assertions.
assert_proper_col_class(field_val, obj_tuple[index])
elif isinstance(field_val, (list, tuple)):
# This field holds a sequence of something.
expected_type = type(obj_tuple[index])
assert type(field_val) is expected_type # noqa: E721
for obj_e, obj_tuple_e in zip(field_val, obj_tuple[index]):
if has(obj_e.__class__):
assert_proper_col_class(obj_e, obj_tuple_e)
elif isinstance(field_val, dict):
orig = field_val
tupled = obj_tuple[index]
assert type(orig) is type(tupled) # noqa: E721
for obj_e, obj_tuple_e in zip(orig.items(),
tupled.items()):
if has(obj_e[0].__class__): # Dict key
assert_proper_col_class(obj_e[0], obj_tuple_e[0])
if has(obj_e[1].__class__): # Dict value
assert_proper_col_class(obj_e[1], obj_tuple_e[1])
assert_proper_col_class(obj, obj_tuple)
@given(st.sampled_from(SEQUENCE_TYPES))
def test_filter(self, C, tuple_factory):
"""
Attributes that are supposed to be skipped are skipped.
"""
assert tuple_factory([tuple_factory([1, ]), ]) == astuple(C(
C(1, 2),
C(3, 4),
), filter=lambda a, v: a.name != "y", tuple_factory=tuple_factory)
@given(container=st.sampled_from(SEQUENCE_TYPES))
def test_lists_tuples(self, container, C):
"""
If recurse is True, also recurse into lists.
"""
assert ((1, [(2, 3), (4, 5), "a"])
== astuple(C(1, container([C(2, 3), C(4, 5), "a"])))
)
@given(st.sampled_from(SEQUENCE_TYPES))
def test_dicts(self, C, tuple_factory):
"""
If recurse is True, also recurse into dicts.
"""
res = astuple(C(1, {"a": C(4, 5)}), tuple_factory=tuple_factory)
assert tuple_factory([1, {"a": tuple_factory([4, 5])}]) == res
assert isinstance(res, tuple_factory)
@given(container=st.sampled_from(SEQUENCE_TYPES))
def test_lists_tuples_retain_type(self, container, C):
"""
If recurse and retain_collection_types are True, also recurse
into lists and do not convert them into list.
"""
assert (
(1, container([(2, 3), (4, 5), "a"]))
== astuple(C(1, container([C(2, 3), C(4, 5), "a"])),
retain_collection_types=True))
@given(container=st.sampled_from(MAPPING_TYPES))
def test_dicts_retain_type(self, container, C):
"""
If recurse and retain_collection_types are True, also recurse
into lists and do not convert them into list.
"""
assert (
(1, container({"a": (4, 5)}))
== astuple(C(1, container({"a": C(4, 5)})),
retain_collection_types=True))
@given(simple_classes(), st.sampled_from(SEQUENCE_TYPES))
def test_roundtrip(self, cls, tuple_class):
"""
Test dumping to tuple and back for Hypothesis-generated classes.
"""
instance = cls()
tuple_instance = astuple(instance, tuple_factory=tuple_class)
assert isinstance(tuple_instance, tuple_class)
roundtrip_instance = cls(*tuple_instance)
assert instance == roundtrip_instance
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.
"""
@attr.s
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`.
"""
@given(slots=st.booleans(), frozen=st.booleans())
def test_empty(self, slots, frozen):
"""
Empty classes without changes get copied.
"""
@attr.s(slots=slots, frozen=frozen)
class C(object):
pass
i1 = C()
with pytest.deprecated_call():
i2 = assoc(i1)
assert i1 is not i2
assert i1 == i2
@given(simple_classes())
def test_no_changes(self, C):
"""
No changes means a verbatim copy.
"""
i1 = C()
with pytest.deprecated_call():
i2 = assoc(i1)
assert i1 is not i2
assert i1 == i2
@given(simple_classes(), st.data())
def test_change(self, C, data):
"""
Changes work.
"""
# Take the first attribute, and change it.
assume(fields(C)) # Skip classes with no attributes.
field_names = [a.name for a in fields(C)]
original = C()
chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
change_dict = {name: data.draw(st.integers())
for name in chosen_names}
with pytest.deprecated_call():
changed = assoc(original, **change_dict)
for k, v in change_dict.items():
assert getattr(changed, k) == v
@given(simple_classes())
def test_unknown(self, C):
"""
Wanting to change an unknown attribute raises an
AttrsAttributeNotFoundError.
"""
# No generated class will have a four letter attribute.
with pytest.raises(AttrsAttributeNotFoundError) as e, \
pytest.deprecated_call():
assoc(C(), aaaa=2)
assert (
"aaaa is not an attrs attribute on {cls!r}.".format(cls=C),
) == e.value.args
def test_frozen(self):
"""
Works on frozen classes.
"""
@attr.s(frozen=True)
class C(object):
x = attr.ib()
y = attr.ib()
with pytest.deprecated_call():
assert C(3, 2) == assoc(C(1, 2), x=3)
def test_warning(self):
"""
DeprecationWarning points to the correct file.
"""
@attr.s
class C(object):
x = attr.ib()
with pytest.warns(DeprecationWarning) as wi:
assert C(2) == assoc(C(1), x=2)
assert __file__ == wi.list[0].filename
class TestEvolve(object):
"""
Tests for `evolve`.
"""
@given(slots=st.booleans(), frozen=st.booleans())
def test_empty(self, slots, frozen):
"""
Empty classes without changes get copied.
"""
@attr.s(slots=slots, frozen=frozen)
class C(object):
pass
i1 = C()
i2 = evolve(i1)
assert i1 is not i2
assert i1 == i2
@given(simple_classes())
def test_no_changes(self, C):
"""
No changes means a verbatim copy.
"""
i1 = C()
i2 = evolve(i1)
assert i1 is not i2
assert i1 == i2
@given(simple_classes(), st.data())
def test_change(self, C, data):
"""
Changes work.
"""
# Take the first attribute, and change it.
assume(fields(C)) # Skip classes with no attributes.
field_names = [a.name for a in fields(C)]
original = C()
chosen_names = data.draw(st.sets(st.sampled_from(field_names)))
# We pay special attention to private attributes, they should behave
# like in `__init__`.
change_dict = {name.replace('_', ''): data.draw(st.integers())
for name in chosen_names}
changed = evolve(original, **change_dict)
for name in chosen_names:
assert getattr(changed, name) == change_dict[name.replace('_', '')]
@given(simple_classes())
def test_unknown(self, C):
"""
Wanting to change an unknown attribute raises an
AttrsAttributeNotFoundError.
"""
# No generated class will have a four letter attribute.
with pytest.raises(TypeError) as e:
evolve(C(), aaaa=2)
expected = "__init__() got an unexpected keyword argument 'aaaa'"
assert (expected,) == e.value.args
def test_validator_failure(self):
"""
TypeError isn't swallowed when validation fails within evolve.
"""
@attr.s
class C(object):
a = attr.ib(validator=instance_of(int))
with pytest.raises(TypeError) as e:
evolve(C(a=1), a="some string")
m = e.value.args[0]
assert m.startswith("'a' must be <{type} 'int'>".format(type=TYPE))
def test_private(self):
"""
evolve() acts as `__init__` with regards to private attributes.
"""
@attr.s
class C(object):
_a = attr.ib()
assert evolve(C(1), a=2)._a == 2
with pytest.raises(TypeError):
evolve(C(1), _a=2)
with pytest.raises(TypeError):
evolve(C(1), a=3, _a=2)
def test_non_init_attrs(self):
"""
evolve() handles `init=False` attributes.
"""
@attr.s
class C(object):
a = attr.ib()
b = attr.ib(init=False, default=0)
assert evolve(C(1), a=2).a == 2

View File

@ -0,0 +1,44 @@
"""
Tests for `__init_subclass__` related tests.
Python 3.6+ only.
"""
import pytest
import attr
@pytest.mark.parametrize("slots", [True, False])
def test_init_subclass_vanilla(slots):
"""
`super().__init_subclass__` can be used if the subclass is not an attrs
class both with dict and slots classes.
"""
@attr.s(slots=slots)
class Base:
def __init_subclass__(cls, param, **kw):
super().__init_subclass__(**kw)
cls.param = param
class Vanilla(Base, param="foo"):
pass
assert "foo" == Vanilla().param
def test_init_subclass_attrs():
"""
`__init_subclass__` works with attrs classes as long as slots=False.
"""
@attr.s(slots=False)
class Base:
def __init_subclass__(cls, param, **kw):
super().__init_subclass__(**kw)
cls.param = param
@attr.s
class Attrs(Base, param="foo"):
pass
assert "foo" == Attrs().param

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,423 @@
"""
Unit tests for slot-related functionality.
"""
import pytest
import attr
from attr._compat import PY2, PYPY, just_warn, make_set_closure_cell
# Pympler doesn't work on PyPy.
try:
from pympler.asizeof import asizeof
has_pympler = True
except BaseException: # Won't be an import error.
has_pympler = False
@attr.s
class C1(object):
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
if not PY2:
def my_class(self):
return __class__ # NOQA: F821
def my_super(self):
"""Just to test out the no-arg super."""
return super().__repr__()
@attr.s(slots=True, hash=True)
class C1Slots(object):
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
if not PY2:
def my_class(self):
return __class__ # NOQA: F821
def my_super(self):
"""Just to test out the no-arg super."""
return super().__repr__()
def test_slots_being_used():
"""
The class is really using __slots__.
"""
non_slot_instance = C1(x=1, y="test")
slot_instance = C1Slots(x=1, y="test")
assert "__dict__" not in dir(slot_instance)
assert "__slots__" in dir(slot_instance)
assert "__dict__" in dir(non_slot_instance)
assert "__slots__" not in dir(non_slot_instance)
assert set(["x", "y"]) == set(slot_instance.__slots__)
if has_pympler:
assert asizeof(slot_instance) < asizeof(non_slot_instance)
non_slot_instance.t = "test"
with pytest.raises(AttributeError):
slot_instance.t = "test"
assert 1 == non_slot_instance.method()
assert 1 == slot_instance.method()
assert attr.fields(C1Slots) == attr.fields(C1)
assert attr.asdict(slot_instance) == attr.asdict(non_slot_instance)
def test_basic_attr_funcs():
"""
Comparison, `__eq__`, `__hash__`, `__repr__`, `attrs.asdict` work.
"""
a = C1Slots(x=1, y=2)
b = C1Slots(x=1, y=3)
a_ = C1Slots(x=1, y=2)
# Comparison.
assert b > a
assert a_ == a
# Hashing.
hash(b) # Just to assert it doesn't raise.
# Repr.
assert "C1Slots(x=1, y=2)" == repr(a)
assert {"x": 1, "y": 2} == attr.asdict(a)
def test_inheritance_from_nonslots():
"""
Inheritance from a non-slot class works.
Note that a slots class inheriting from an ordinary class loses most of the
benefits of slots classes, but it should still work.
"""
@attr.s(slots=True, hash=True)
class C2Slots(C1):
z = attr.ib()
c2 = C2Slots(x=1, y=2, z="test")
assert 1 == c2.x
assert 2 == c2.y
assert "test" == c2.z
c2.t = "test" # This will work, using the base class.
assert "test" == c2.t
assert 1 == c2.method()
assert "clsmethod" == c2.classmethod()
assert "staticmethod" == c2.staticmethod()
assert set(["z"]) == set(C2Slots.__slots__)
c3 = C2Slots(x=1, y=3, z="test")
assert c3 > c2
c2_ = C2Slots(x=1, y=2, z="test")
assert c2 == c2_
assert "C2Slots(x=1, y=2, z='test')" == repr(c2)
hash(c2) # Just to assert it doesn't raise.
assert {"x": 1, "y": 2, "z": "test"} == attr.asdict(c2)
def test_nonslots_these():
"""
Enhancing a non-slots class using 'these' works.
This will actually *replace* the class with another one, using slots.
"""
class SimpleOrdinaryClass(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
C2Slots = attr.s(these={"x": attr.ib(), "y": attr.ib(), "z": attr.ib()},
init=False, slots=True, hash=True)(SimpleOrdinaryClass)
c2 = C2Slots(x=1, y=2, z="test")
assert 1 == c2.x
assert 2 == c2.y
assert "test" == c2.z
with pytest.raises(AttributeError):
c2.t = "test" # We have slots now.
assert 1 == c2.method()
assert "clsmethod" == c2.classmethod()
assert "staticmethod" == c2.staticmethod()
assert set(["x", "y", "z"]) == set(C2Slots.__slots__)
c3 = C2Slots(x=1, y=3, z="test")
assert c3 > c2
c2_ = C2Slots(x=1, y=2, z="test")
assert c2 == c2_
assert "SimpleOrdinaryClass(x=1, y=2, z='test')" == repr(c2)
hash(c2) # Just to assert it doesn't raise.
assert {"x": 1, "y": 2, "z": "test"} == attr.asdict(c2)
def test_inheritance_from_slots():
"""
Inheriting from an attr slot class works.
"""
@attr.s(slots=True, hash=True)
class C2Slots(C1Slots):
z = attr.ib()
@attr.s(slots=True, hash=True)
class C2(C1):
z = attr.ib()
c2 = C2Slots(x=1, y=2, z="test")
assert 1 == c2.x
assert 2 == c2.y
assert "test" == c2.z
assert set(["z"]) == set(C2Slots.__slots__)
assert 1 == c2.method()
assert "clsmethod" == c2.classmethod()
assert "staticmethod" == c2.staticmethod()
with pytest.raises(AttributeError):
c2.t = "test"
non_slot_instance = C2(x=1, y=2, z="test")
if has_pympler:
assert asizeof(c2) < asizeof(non_slot_instance)
c3 = C2Slots(x=1, y=3, z="test")
assert c3 > c2
c2_ = C2Slots(x=1, y=2, z="test")
assert c2 == c2_
assert "C2Slots(x=1, y=2, z='test')" == repr(c2)
hash(c2) # Just to assert it doesn't raise.
assert {"x": 1, "y": 2, "z": "test"} == attr.asdict(c2)
def test_bare_inheritance_from_slots():
"""
Inheriting from a bare attr slot class works.
"""
@attr.s(init=False, cmp=False, hash=False, repr=False, slots=True)
class C1BareSlots(object):
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
@attr.s(init=False, cmp=False, hash=False, repr=False)
class C1Bare(object):
x = attr.ib(validator=attr.validators.instance_of(int))
y = attr.ib()
def method(self):
return self.x
@classmethod
def classmethod(cls):
return "clsmethod"
@staticmethod
def staticmethod():
return "staticmethod"
@attr.s(slots=True, hash=True)
class C2Slots(C1BareSlots):
z = attr.ib()
@attr.s(slots=True, hash=True)
class C2(C1Bare):
z = attr.ib()
c2 = C2Slots(x=1, y=2, z="test")
assert 1 == c2.x
assert 2 == c2.y
assert "test" == c2.z
assert 1 == c2.method()
assert "clsmethod" == c2.classmethod()
assert "staticmethod" == c2.staticmethod()
with pytest.raises(AttributeError):
c2.t = "test"
non_slot_instance = C2(x=1, y=2, z="test")
if has_pympler:
assert asizeof(c2) < asizeof(non_slot_instance)
c3 = C2Slots(x=1, y=3, z="test")
assert c3 > c2
c2_ = C2Slots(x=1, y=2, z="test")
assert c2 == c2_
assert "C2Slots(x=1, y=2, z='test')" == repr(c2)
hash(c2) # Just to assert it doesn't raise.
assert {"x": 1, "y": 2, "z": "test"} == attr.asdict(c2)
@pytest.mark.skipif(PY2, reason="closure cell rewriting is PY3-only.")
class TestClosureCellRewriting(object):
def test_closure_cell_rewriting(self):
"""
Slot classes support proper closure cell rewriting.
This affects features like `__class__` and the no-arg super().
"""
non_slot_instance = C1(x=1, y="test")
slot_instance = C1Slots(x=1, y="test")
assert non_slot_instance.my_class() is C1
assert slot_instance.my_class() is C1Slots
# Just assert they return something, and not an exception.
assert non_slot_instance.my_super()
assert slot_instance.my_super()
def test_inheritance(self):
"""
Slot classes support proper closure cell rewriting when inheriting.
This affects features like `__class__` and the no-arg super().
"""
@attr.s
class C2(C1):
def my_subclass(self):
return __class__ # NOQA: F821
@attr.s
class C2Slots(C1Slots):
def my_subclass(self):
return __class__ # NOQA: F821
non_slot_instance = C2(x=1, y="test")
slot_instance = C2Slots(x=1, y="test")
assert non_slot_instance.my_class() is C1
assert slot_instance.my_class() is C1Slots
# Just assert they return something, and not an exception.
assert non_slot_instance.my_super()
assert slot_instance.my_super()
assert non_slot_instance.my_subclass() is C2
assert slot_instance.my_subclass() is C2Slots
@pytest.mark.parametrize("slots", [True, False])
def test_cls_static(self, slots):
"""
Slot classes support proper closure cell rewriting for class- and
static methods.
"""
# Python can reuse closure cells, so we create new classes just for
# this test.
@attr.s(slots=slots)
class C:
@classmethod
def clsmethod(cls):
return __class__ # noqa: F821
assert C.clsmethod() is C
@attr.s(slots=slots)
class D:
@staticmethod
def statmethod():
return __class__ # noqa: F821
assert D.statmethod() is D
@pytest.mark.skipif(
PYPY,
reason="ctypes are used only on CPython"
)
def test_missing_ctypes(self, monkeypatch):
"""
Keeps working if ctypes is missing.
A warning is emitted that points to the actual code.
"""
monkeypatch.setattr(attr._compat, "import_ctypes", lambda: None)
func = make_set_closure_cell()
with pytest.warns(RuntimeWarning) as wr:
func()
w = wr.pop()
assert __file__ == w.filename
assert (
"Missing ctypes. Some features like bare super() or accessing "
"__class__ will not work with slots classes.",
) == w.message.args
assert just_warn is func

View File

@ -0,0 +1,266 @@
"""
Tests for `attr.validators`.
"""
from __future__ import absolute_import, division, print_function
import pytest
import zope.interface
import attr
from attr import has
from attr import validators as validator_module
from attr._compat import TYPE
from attr.validators import and_, in_, instance_of, optional, provides
from .utils import simple_attr
class TestInstanceOf(object):
"""
Tests for `instance_of`.
"""
def test_success(self):
"""
Nothing happens if types match.
"""
v = instance_of(int)
v(None, simple_attr("test"), 42)
def test_subclass(self):
"""
Subclasses are accepted too.
"""
v = instance_of(int)
# yep, bools are a subclass of int :(
v(None, simple_attr("test"), True)
def test_fail(self):
"""
Raises `TypeError` on wrong types.
"""
v = 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 = instance_of(int)
assert (
"<instance_of validator for type <{type} 'int'>>"
.format(type=TYPE)
) == repr(v)
def always_pass(_, __, ___):
"""
Toy validator that always passses.
"""
def always_fail(_, __, ___):
"""
Toy validator that always fails.
"""
0/0
class TestAnd(object):
def test_success(self):
"""
Succeeds if all wrapped validators succeed.
"""
v = and_(instance_of(int), always_pass)
v(None, simple_attr("test"), 42)
def test_fail(self):
"""
Fails if any wrapped validator fails.
"""
v = and_(instance_of(int), always_fail)
with pytest.raises(ZeroDivisionError):
v(None, simple_attr("test"), 42)
def test_sugar(self):
"""
`and_(v1, v2, v3)` and `[v1, v2, v3]` are equivalent.
"""
@attr.s
class C(object):
a1 = attr.ib("a1", validator=and_(
instance_of(int),
))
a2 = attr.ib("a2", validator=[
instance_of(int),
])
assert C.__attrs_attrs__[0].validator == C.__attrs_attrs__[1].validator
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 (
"<provides validator for interface {interface!r}>"
.format(interface=IFoo)
) == repr(v)
@pytest.mark.parametrize("validator", [
instance_of(int),
[always_pass, instance_of(int)],
])
class TestOptional(object):
"""
Tests for `optional`.
"""
def test_success(self, validator):
"""
Nothing happens if validator succeeds.
"""
v = optional(validator)
v(None, simple_attr("test"), 42)
def test_success_with_none(self, validator):
"""
Nothing happens if None.
"""
v = optional(validator)
v(None, simple_attr("test"), None)
def test_fail(self, validator):
"""
Raises `TypeError` on wrong types.
"""
v = optional(validator)
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, validator):
"""
Returned validator has a useful `__repr__`.
"""
v = optional(validator)
if isinstance(validator, list):
assert (
("<optional validator for _AndValidator(_validators=[{func}, "
"<instance_of validator for type <{type} 'int'>>]) or None>")
.format(func=repr(always_pass), type=TYPE)
) == repr(v)
else:
assert (
("<optional validator for <instance_of validator for type "
"<{type} 'int'>> or None>")
.format(type=TYPE)
) == repr(v)
class TestIn_(object):
"""
Tests for `in_`.
"""
def test_success_with_value(self):
"""
If the value is in our options, nothing happens.
"""
v = in_([1, 2, 3])
a = simple_attr("test")
v(1, a, 3)
def test_fail(self):
"""
Raise ValueError if the value is outside our options.
"""
v = in_([1, 2, 3])
a = simple_attr("test")
with pytest.raises(ValueError) as e:
v(None, a, None)
assert (
"'test' must be in [1, 2, 3] (got None)",
) == e.value.args
def test_repr(self):
"""
Returned validator has a useful `__repr__`.
"""
v = in_([3, 4, 5])
assert(
("<in_ validator with options [3, 4, 5]>")
) == repr(v)
def test_hashability():
"""
Validator classes are hashable.
"""
for obj_name in dir(validator_module):
obj = getattr(validator_module, obj_name)
if not has(obj):
continue
hash_func = getattr(obj, '__hash__', None)
assert hash_func is not None
assert hash_func is not object.__hash__

48
third_party/python/attrs/tests/utils.py vendored Normal file
View File

@ -0,0 +1,48 @@
"""
Common helper functions for tests.
"""
from __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, str=False, slots=False,
frozen=False):
"""
Return a new simple class.
"""
return make_class(
"C", ["a", "b"],
cmp=cmp, repr=repr, hash=hash, init=True, slots=slots, str=str,
frozen=frozen,
)
def simple_attr(name, default=NOTHING, validator=None, repr=True,
cmp=True, hash=None, init=True, converter=None):
"""
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, converter=converter,
)
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()

88
third_party/python/attrs/tox.ini vendored Normal file
View File

@ -0,0 +1,88 @@
[tox]
envlist = isort,py27,py34,py35,py36,pypy,pypy3,flake8,manifest,docs,readme,changelog,coverage-report
[testenv]
# Prevent random setuptools/pip breakages like
# https://github.com/pypa/setuptools/issues/1042 from breaking our builds.
setenv =
VIRTUALENV_NO_DOWNLOAD=1
extras = tests
commands = python -m pytest {posargs}
[testenv:py27]
extras = tests
commands = coverage run --parallel -m pytest {posargs}
[testenv:py36]
# Python 3.6+ has a number of compile-time warnings on invalid string escapes.
# PYTHONWARNINGS=d and --no-compile below make them visible during the Tox run.
install_command = pip install --no-compile {opts} {packages}
setenv =
PYTHONWARNINGS=d
extras = tests
commands = coverage run --parallel -m pytest {posargs}
# Uses default basepython otherwise reporting doesn't work on Travis where
# Python 3.6 is only available in 3.6 jobs.
[testenv:coverage-report]
deps = coverage
skip_install = true
commands =
coverage combine
coverage report
[testenv:flake8]
basepython = python3.6
extras = tests
# Needs a full install so isort can determine own/foreign imports.
deps =
flake8
flake8-isort
commands = flake8 src tests setup.py conftest.py docs/conf.py
[testenv:isort]
basepython = python3.6
extras = tests
# Needs a full install so isort can determine own/foreign imports.
deps =
isort
commands =
isort --recursive setup.py conftest.py src tests
[testenv:docs]
basepython = python3.6
setenv =
PYTHONHASHSEED = 0
extras = docs
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]
basepython = python3.6
deps = check-manifest
skip_install = true
commands = check-manifest
[testenv:readme]
basepython = python3.6
deps = readme_renderer
skip_install = true
commands = python setup.py check -r -s
[testenv:changelog]
basepython = python3.6
deps = towncrier
skip_install = true
commands = towncrier --draft

View File

@ -11,6 +11,9 @@ with Files('**'):
with Files('PyECC/**'):
BUG_COMPONENT = ('Core', 'Security: PSM')
with Files('attrs/**'):
BUG_COMPONENT = ('Taskcluster', 'Task Configuration')
with Files('blessings/**'):
BUG_COMPONENT = ('Firefox Build System', 'General')