pax_global_header00006660000000000000000000000064132216444430014515gustar00rootroot0000000000000052 comment=ca06613b750936f6edd315cd94e5c7de0db6580d attrs-17.4.0/000077500000000000000000000000001322164444300127435ustar00rootroot00000000000000attrs-17.4.0/.coveragerc000066400000000000000000000002531322164444300150640ustar00rootroot00000000000000[run] branch = True source = attr [paths] source = src/attr .tox/*/lib/python*/site-packages/attr .tox/pypy/site-packages/attr [report] show_missing = True attrs-17.4.0/.github/000077500000000000000000000000001322164444300143035ustar00rootroot00000000000000attrs-17.4.0/.github/CODE_OF_CONDUCT.rst000066400000000000000000000062621322164444300173200ustar00rootroot00000000000000Contributor 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 `_, version 1.4, available at . attrs-17.4.0/.github/CONTRIBUTING.rst000066400000000000000000000204341322164444300167470ustar00rootroot00000000000000How To Contribute ================= First off, thank you for considering contributing to ``attrs``! It's people like *you* who make it is such a great tool for everyone. This document is mainly to help you to get started by codifying tribal knowledge and expectations and make it more accessible to everyone. But 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 `_! The offical tag is ``python-attrs`` and helping out in support frees us up for improving ``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. - Don’t 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 you find in ``tests/util.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 in 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 to 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 number 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 monospaced font. - If you mention functions or other callables, add parantheses at the end of their names: ``attr.func()`` or ``attr.Class.method()``. This makes the changelog a lot more readable. - Prefer simple past 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 you’ll probably want a more traditional environment too. 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 `_. It’s out of scope for this document to list all the ways to manage virtual environments in Python but if you don’t have already a pet way, take some time to look at tools like `pew `_, `virtualfish `_, and `virtualenvwrapper `_. 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 for 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 attrs-17.4.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000022121322164444300201010ustar00rootroot00000000000000# Pull Request Check List This is just a reminder about the most common mistakes. Please make sure that you tick all *appropriate* boxes. But please read our [contribution guide](http://www.attrs.org/en/latest/contributing.html) at least once, it will save you unnecessary review cycles! - [ ] Added **tests** for changed code. - [ ] New features have been added to our [Hypothesis testing strategy](https://github.com/python-attrs/attrs/blob/master/tests/utils.py). - [ ] Updated **documentation** for changed code. - [ ] Documentation in `.rst` files is written using [semantic newlines](http://rhodesmill.org/brandon/2012/one-sentence-per-line/). - [ ] Changed/added classes/methods/functions have appropriate `versionadded`, `versionchanged`, or `deprecated` [directives](http://www.sphinx-doc.org/en/stable/markup/para.html#directive-versionadded). - [ ] Changes (and possible deprecations) have news fragments in [`changelog.d`](https://github.com/python-attrs/attrs/blob/master/changelog.d). If you have *any* questions to *any* of the points above, just **submit and ask**! This checklist is here to *help* you, not to deter you from contributing! attrs-17.4.0/.gitignore000066400000000000000000000001151322164444300147300ustar00rootroot00000000000000.tox .coverage* *.pyc *.egg-info docs/_build/ htmlcov dist .cache .hypothesisattrs-17.4.0/.readthedocs.yml000066400000000000000000000001161322164444300160270ustar00rootroot00000000000000--- python: version: 3 pip_install: true extra_requirements: - docs attrs-17.4.0/.travis.yml000066400000000000000000000016751322164444300150650ustar00rootroot00000000000000dist: trusty sudo: false cache: directories: - $HOME/.cache/pip language: python matrix: fast_finish: true include: - python: "2.7" env: TOXENV=py27 - python: "3.4" env: TOXENV=py34 - python: "3.5" env: TOXENV=py35 - python: "3.6" env: TOXENV=py36 - python: "pypy2.7-5.8.0" env: TOXENV=pypy - python: "pypy3.5-5.8.0" env: TOXENV=pypy3 # Prevent breakage by a new release - python: "3.6-dev" env: TOXENV=py36 # Meta - python: "3.6" env: TOXENV=flake8 - python: "3.6" env: TOXENV=manifest - python: "3.6" env: TOXENV=docs - python: "3.6" env: TOXENV=readme - python: "3.6" env: TOXENV=changelog allow_failures: python: "3.6-dev" install: - pip install tox script: - tox before_install: - pip install codecov after_success: - tox -e coverage-report - codecov notifications: email: false attrs-17.4.0/AUTHORS.rst000066400000000000000000000013611322164444300146230ustar00rootroot00000000000000Credits ======= ``attrs`` is written and maintained by `Hynek Schlawack `_. The development is kindly supported by `Variomedia AG `_. A full list of contributors can be found in `GitHub's overview `_. It’s the spiritual successor of `characteristic `_ and aspires to fix some of it clunkiness and unfortunate decisions. Both were inspired by Twisted’s `FancyEqMixin `_ but both are implemented using class decorators because `sub-classing is bad for you `_, m’kay? attrs-17.4.0/CHANGELOG.rst000066400000000000000000000435501322164444300147730ustar00rootroot00000000000000Changelog ========= Versions follow `CalVer `_ with a strict backwards compatibility policy. The third digit is only for regressions. .. towncrier release notes start 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 `_, `#299 `_, `#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 `_ 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 `_ 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 `_, `#295 `_, `#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 `_ - ``ctypes`` is optional now however if it's missing, a bare ``super()`` will not work in slots classes. This should only happen in special environments like Google App Engine. `#284 `_, `#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 `_, `#287 `_ - Subclasses of ``auto_attribs=True`` can be empty now. `#291 `_, `#292 `_ - Equality tests are *much* faster now. `#306 `_ - All generated methods now have correct ``__module__``, ``__name__``, and (on Python 3) ``__qualname__`` attributes. `#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 `_) Changes ^^^^^^^ - ``super()`` and ``__class__`` now work on Python 3 when ``slots=True``. (`#102 `_, `#226 `_, `#269 `_, `#270 `_, `#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 `_). (`#151 `_, `#214 `_, `#215 `_, `#239 `_) - The combination of ``str=True`` and ``slots=True`` now works on Python 2. (`#198 `_) - ``attr.Factory`` is hashable again. (`#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 `_, `#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 `_, `#277 `_) - Instances of classes created using ``attr.make_class()`` can now be pickled. (`#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 `_ ---- 17.1.0 (2017-05-16) ------------------- To encourage more participation, the project has also been moved into a `dedicated GitHub organization `_ 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 `_. 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 `_ - 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 `_ `#124 `_ `#135 `_ - ``FrozenInstanceError`` is now raised when trying to delete an attribute from a frozen class. `#118 `_ - Frozen-ness of classes is now inherited. `#128 `_ - ``__attrs_post_init__()`` is now run if validation is disabled. `#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 `_ - Added ``attr.validators.and_()`` that composes multiple validators into one. `#161 `_ - For convenience, the ``validator`` argument of ``@attr.s`` now can take a ``list`` of validators that are wrapped using ``and_()``. `#138 `_ - Accordingly, ``attr.validators.optional()`` now can take a ``list`` of validators too. `#161 `_ - Validators can now be defined conveniently inline by using the attribute as a decorator. Check out the `examples `_ to see it in action! `#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 `_ - 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 `_ `#173 `_ - ``attr.make_class()`` now accepts the keyword argument ``bases`` which allows for subclassing. `#152 `_ - Metaclasses are now preserved with ``slots=True``. `#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 `_ - Allow for a ``__attrs_post_init__()`` method that -- if defined -- will get called at the end of the ``attrs``-generated ``__init__()`` method. `#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 `_ ---- 16.2.0 (2016-09-17) ------------------- Changes: ^^^^^^^^ - Added ``attr.astuple()`` that -- similarly to ``attr.asdict()`` -- returns the instance as a tuple. `#77 `_ - Converts now work with frozen classes. `#76 `_ - Instantiation of ``attrs`` classes with converters is now significantly faster. `#80 `_ - Pickling now works with ``__slots__`` classes. `#81 `_ - ``attr.assoc()`` now works with ``__slots__`` classes. `#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 ``__slots__`` classes. `#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 `_ - ``attr.asdict()``, ``attr.has()`` and ``attr.fields()`` are significantly faster. `#48 `_ `#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 `_ - ``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 `_ ---- 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 `slots `_-style (and save your precious memory) just by passing ``slots=True``. `#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 `_ - ``attr.asdict()`` can now produce arbitrary mappings instead of Python ``dict``\ s when provided with a ``dict_factory`` argument. `#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 `_ - Speed up object creation when attribute validators are used. `#28 `_ ---- 15.1.0 (2015-08-20) ------------------- Changes: ^^^^^^^^ - Added ``attr.validators.optional()`` that wraps other validators allowing attributes to be ``None``. `#16 `_ - Multi-level inheritance now works. `#24 `_ - ``__repr__()`` now works with non-redecorated subclasses. `#20 `_ ---- 15.0.0 (2015-04-15) ------------------- Changes: ^^^^^^^^ Initial release. attrs-17.4.0/LICENSE000066400000000000000000000020721322164444300137510ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2015 Hynek Schlawack Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. attrs-17.4.0/MANIFEST.in000066400000000000000000000011031322164444300144740ustar00rootroot00000000000000include 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 attrs-17.4.0/README.rst000066400000000000000000000111211322164444300144260ustar00rootroot00000000000000.. 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 `_ 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 `_ ``namedtuple``\ s. Which in turn encourages you to write *small classes* that do `one thing well `_. Never again violate the `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 `_, `Automat `_, and other open source software, in `The One Python Library Everyone Needs `_: I’m 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 I’ve see it used in. **Kenneth Reitz**, author of `requests `_, Python Overlord at Heroku, `on paper no less `_: 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 `_ 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 `_ license, its documentation lives at `Read the Docs `_, the code on `GitHub `_, and the latest release on `PyPI `_. It’s rigorously tested on Python 2.7, 3.4+, and PyPy. If you'd like to contribute you're most welcome and we've written `a little guide `_ to get you started! attrs-17.4.0/changelog.d/000077500000000000000000000000001322164444300151145ustar00rootroot00000000000000attrs-17.4.0/changelog.d/.gitignore000066400000000000000000000000001322164444300170720ustar00rootroot00000000000000attrs-17.4.0/changelog.d/261.change.rst000066400000000000000000000003421322164444300174010ustar00rootroot00000000000000Generated ``__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. attrs-17.4.0/changelog.d/280.change.rst000066400000000000000000000002751322164444300174070ustar00rootroot00000000000000``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. attrs-17.4.0/changelog.d/284.change.rst000066400000000000000000000002571322164444300174130ustar00rootroot00000000000000``ctypes`` is optional now however if it's missing, a bare ``super()`` will not work in slots classes. This should only happen in special environments like Google App Engine. attrs-17.4.0/changelog.d/285.change.rst000066400000000000000000000003331322164444300174070ustar00rootroot00000000000000The 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. attrs-17.4.0/changelog.d/286.change.rst000066400000000000000000000002571322164444300174150ustar00rootroot00000000000000``ctypes`` is optional now however if it's missing, a bare ``super()`` will not work in slots classes. This should only happen in special environments like Google App Engine. attrs-17.4.0/changelog.d/287.change.rst000066400000000000000000000003331322164444300174110ustar00rootroot00000000000000The 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. attrs-17.4.0/changelog.d/291.change.rst000066400000000000000000000000661322164444300174070ustar00rootroot00000000000000Subclasses of ``auto_attribs=True`` can be empty now. attrs-17.4.0/changelog.d/292.change.rst000066400000000000000000000000661322164444300174100ustar00rootroot00000000000000Subclasses of ``auto_attribs=True`` can be empty now. attrs-17.4.0/changelog.d/295.change.rst000066400000000000000000000003421322164444300174100ustar00rootroot00000000000000Generated ``__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. attrs-17.4.0/changelog.d/296.change.rst000066400000000000000000000003421322164444300174110ustar00rootroot00000000000000Generated ``__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. attrs-17.4.0/changelog.d/298.breaking.rst000066400000000000000000000012201322164444300177440ustar00rootroot00000000000000The 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. attrs-17.4.0/changelog.d/299.breaking.rst000066400000000000000000000012201322164444300177450ustar00rootroot00000000000000The 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. attrs-17.4.0/changelog.d/304.breaking.rst000066400000000000000000000012201322164444300177300ustar00rootroot00000000000000The 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. attrs-17.4.0/changelog.d/306.change.rst000066400000000000000000000000461322164444300174020ustar00rootroot00000000000000Equality tests are *much* faster now. attrs-17.4.0/changelog.d/307.deprecation.rst000066400000000000000000000004401322164444300204510ustar00rootroot00000000000000The ``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``. attrs-17.4.0/changelog.d/308.breaking.rst000066400000000000000000000012211322164444300177350ustar00rootroot00000000000000The ``__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 attrs-17.4.0/changelog.d/309.change.rst000066400000000000000000000001641322164444300174060ustar00rootroot00000000000000All generated methods now have correct ``__module__``, ``__name__``, and (on Python 3) ``__qualname__`` attributes. attrs-17.4.0/changelog.d/towncrier_template.rst000066400000000000000000000014411322164444300215550ustar00rootroot00000000000000{% 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 %} ---- attrs-17.4.0/conftest.py000066400000000000000000000007731322164444300151510ustar00rootroot00000000000000from __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", ]) attrs-17.4.0/docs/000077500000000000000000000000001322164444300136735ustar00rootroot00000000000000attrs-17.4.0/docs/Makefile000066400000000000000000000151461322164444300153420ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/attrs.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/attrs.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/attrs" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/attrs" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." attrs-17.4.0/docs/_static/000077500000000000000000000000001322164444300153215ustar00rootroot00000000000000attrs-17.4.0/docs/_static/attrs_logo.png000066400000000000000000000167271322164444300202210ustar00rootroot00000000000000PNG  IHDR~; sBIT|d pHYs+tEXtSoftwarewww.inkscape.org<TIDATx{|Wyϙjl'%sv-9&NG(oRJ Iymmӷ6P @ڄ[1@bllegfumؒeZiw?vvvfV磏sΜgB)[D2!"c @[[$k5 ſKD7_,#.0z{{#Afc3i;Vx] ."LnQJ}׉$3_NDI\ "a n wL&oTJ}_ !nLӻf^L$VJRR ۘ9?ZA p]@H)pM*f)m̦Rԅp] [n7+f*.D"I){WʻYž c(Z4,ᴡ~mDP6A,{ua]wL< !KS1J4 _O CDS FW\ y%JE'&&SgQ=tzrD8H6݆+.t)n*o0- ~rM8mD"6Qۉd^e[fV 0_ W0Y wPÓ,3n!`;̃.n4{J,[E."iPBD>4?T4{޺*o}X]Me"z@a>Z"`e օГ" :::Z[[_ @U#Rj`%{5[B /3 DկkS۫n^ }Žu%Tv{#3_1zU8~MD p;7 n.H\T!Ht{l@AR|5]/,UjPZd7km$!̼Rd2Q7G"|SRR .f~-3ȖZvUp Ol_:Dtaߩ/)ޝd[oANNQK)8.=(?($; !uӹzNNQ%WJAO"a[ QL& f~r+u=N?, E?fMiޖ|1qm,8j \W[c歖e=Wpƍ?YRQ8d`TΏu: e]iLpo(r"f?Ү>e#f~iKMӼh||J}Mo1MfS\ɔf!ۧ4AT+7mcG_ -EDV\4ͯwaTӆd2١zw '|!m% ?3  ЯlpoyTjI#-R^)ĨYv%˲4J)"˲[F!OؒdRKr }[F!G^)gМ_r6ͮjƝ?h 'bXQhiC<p!;fDt>I~Z>4j&f\=PJL&8f%3{j5nɂ J)?Cq>vM;p~0#MRR[n]f~زm!o!£>ʽDzG*V`#o2l%"!8.x/,!"3̜ :Jys90^>"Dٴo[i(- >Zݧg@?CC)Q4nkk ;x_Z?T^4Nwa<=f%d͏{fn3TiZZZ<14 OD^14"ru$kŭ6O)R~1_A[g }}}G3mnN7a-B]Rʧļ4lxȃg:}hhhRnWS1H#x>E4i?m6xt]!}xf+gSD{4/yOm7 Q'!f~":JhEfW3K>n{At 4ܜwhh(iRjN4G3z (4򎏏?1DpŔ3BX'YTqfzQ 4ט٢Z̛ ^4n4Rlx?(n[-DӰFFF&WZכЏ`ro\5ĉ*?br^zŋw(d0wY5\oA68-N-lhaYo9T^R^O.9ᴡFv[VZ z2---jtttN,ސhȭaw[RݩTjIhtVyo_PpOVy_oJpRf4ToAfU^Al#(Ɣ(gpI 6W\ѬʫLӼ? W~ns !x<*!.vc'?lY_Ͼ~}.Ǧi~ d A+/Py.rܖK)wĕ4ϖ*H&\ne!8Ѵ3d2jdddw[[--- !ޜdRW\yKGFFJ{:zhرcᎂ#oH)⎀bs:y" swW` ; \!eHRǏ/B,F'ZZZ;UoBBBBBBBBBBBBBBBBBBBBBBBBBLrDt 3_vc=]pRT4^`Rj3ELӼ^42MgJD`bf談B\?11q#tA,4,aM? 0K (&OiV8 |>pR^f̩P(CNFHuFT gH$$)B(U+LR=tUյ@CЛFy;;;pJD"G?pVM---IW9k5z7bYVi%B6R"ZbԚ1":'d9F}}}/zN(|OCEdk>ׅ% ̋&y1fBDt p%uwwrSDJQ": ` 3Rm7|vP%\b\6o|D3P)L&3T<ZӴ2m壡>Y rR[k)CL.32MBa@ .Je2Nzzzr2[_.<'"i;a/rs]4GMPJKP"0J:" :BtiéR" f~ãokKv!;"@G}E_a}hoqࣚ=d?%@˓^L#4E_Fq+W@D= 6foIfBD#K)7Ŗ_t] TsDb3W_Rx| qX]Vy[ZZ4@a:R: e0˔i8@Yّd~X3uv͹we$(owwYΠeaRd2&"AJz{{#(Fe=o{|sׯp],Yl'M/ !N(Q,'sg9SH$/ v1Ͽ&''\R fj&h388x*'QL3n"s !&9ZLDKyh# 3B(&zcJEBU̼V[w)u)XI4(>w.H)v۷g_$(~\BOʕѧRW#'3pe5fO9nor(K)UUvwԏY&E0sW7ۜʙ˲>E`-DrpIBdrr졡n:-H8hcʧD"eP e}ͩ=' ø5 9-b{[g6>oY^"LnbkT^0~7;T)`r|M5hIFD"H\N2XROPtY60Fr{'}qkl}c^GDv*gylS^!2jیkkm>̯s*VJ}.O4M5~yT=UD" !eB2v"*k̿(w^i$wsSggH$B `3/aB08+( / ڪvdr(Xhfjv sO v\IS5khS6jv9m=b+ŊDfinD"~Χu}n\ RTtbbr Ue7onqڷϥOx D`:GyO[7NWj!UNfwqU̾111 T~> r(;zΎ9X ?03PJAJ '8 =t&:5>Gye@QbMn89qi_dR.pCVRjFv |Y)]fb&nടN<3Z$rnzdRJg62/; 2NA)wr评Gwͬpf XZ_&_"©=2@>?ufXT*PiNYEUa0=GJ6B*/.خ6PHd}f2mil9"H9y+- v=":`L)5ml"dMDt*[U.`zaO0+LLsV%Tae:c0>㺮oB\W@IZQJ6~Eya{79nIDPGZbUcm7'q4[ H*$3GrW8]nEN=m"+78ܗ1MK(cI_۷gOgf>FD%p٩v`E*p ms+֙Bv2yC>'O,C;MB4u3sT_h'~P-re57u޽;{HJ QӴ3_ `^Aܻm'N=pU|7dɒ޵^}p9)o9?Ee/ylknFHr5c= ADw{.Hc-.?e8? Dt'3 J)czpLӴeBa%$≉a{[rӡXF/I)&+ ' %B:f8Ixp8q\MӜRQjI܎]H.f>϶ Yc{2S |6p%3_ 13c(ڽpBQJ噙h$%\9vhP(9n[P^GjigDNqQ5| L[O?gZx33 W":gnv{f3_Zả&ԩ ?*e(̮ Klg=Tn"|Oj;t]+߶,}bl?^pJXU&}%p[oԿ+(>Ç/ɾ"*kHGs|I)!#X\`fO}*WJ}tz{7~~R\!'vاvKkro99,:x?|0}eU>EZU6*0nݺEXD̽(|I(*.f;*eqCWWH$r0wI_5MZe!pBJ)GfW;hJ^"eq@e]2 tc<E"3oPJ%l%fcT̝u7٬WHd"b(\9cDtDg|2WL&̼{i3/B+&Q b~DtT)eify/Ԑ>^}IENDB`attrs-17.4.0/docs/_static/attrs_logo.svg000066400000000000000000000152051322164444300202220ustar00rootroot00000000000000attrs-17.4.0/docs/api.rst000066400000000000000000000263751322164444300152130ustar00rootroot00000000000000.. _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) .. 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 = 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() Influencing Initialization ++++++++++++++++++++++++++ Generally speaking, it's best to keep logic out of your ``__init__``. The moment you need a finer control over how your class is instantiated, it's usually best to use a classmethod factory or to apply the `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 ` 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) .. _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.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 (got '1' that is a ).", Attribute(name='x', default=NOTHING, validator=>, repr=True, cmp=True, hash=None, init=True, type=None), , '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 (got '42' that is a ).", Attribute(name='x', default=NOTHING, validator=>, type=None), , '42') >>> C(None) Traceback (most recent call last): ... TypeError: ("'x' must be (got None that is a ).", Attribute(name='x', default=NOTHING, validator=>, repr=True, cmp=True, hash=None, init=True, type=None), , 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=, val=1) >>> C("on", 1) Traceback (most recent call last): ... ValueError: 'state' must be in (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 (got '42' that is a ).", Attribute(name='x', default=NOTHING, validator=>, type=None), , '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 attrs-17.4.0/docs/backward-compatibility.rst000066400000000000000000000015241322164444300210540ustar00rootroot00000000000000Backward Compatibility ====================== .. currentmodule:: attr ``attrs`` has a very strong backward compatibility policy that is inspired by the policy of the `Twisted framework `_. 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. attrs-17.4.0/docs/changelog.rst000066400000000000000000000000361322164444300163530ustar00rootroot00000000000000.. include:: ../CHANGELOG.rst attrs-17.4.0/docs/conf.py000066400000000000000000000113371322164444300151770ustar00rootroot00000000000000# -*- 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 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'] attrs-17.4.0/docs/contributing.rst000066400000000000000000000001511322164444300171310ustar00rootroot00000000000000.. _contributing: .. include:: ../.github/CONTRIBUTING.rst .. include:: ../.github/CODE_OF_CONDUCT.rst attrs-17.4.0/docs/docutils.conf000066400000000000000000000000651322164444300163710ustar00rootroot00000000000000[parsers] [restructuredtext parser] smart_quotes=yes attrs-17.4.0/docs/examples.rst000066400000000000000000000525321322164444300162520ustar00rootroot00000000000000.. _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 `_, 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 `_. In Python 3, classes defined within other classes are `detected `_ and reflected in the ``__repr__``. In Python 2 though, it's impossible. Therefore ``@attr.s`` comes with the ``repr_ns`` option to set it manually: .. doctest:: >>> @attr.s ... class C(object): ... @attr.s(repr_ns="C") ... class D(object): ... pass >>> C.D() C.D() ``repr_ns`` works on both Python 2 and 3. On Python 3 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 ` or :func:`exclude ` certain types or attributes, ``attrs`` ships with a few helpers: .. doctest:: >>> @attr.s ... class User(object): ... login = attr.ib() ... password = attr.ib() ... id = attr.ib() >>> attr.asdict( ... User("jane", "s33kred", 42), ... filter=attr.filters.exclude(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()) >>> 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 `_. 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) .. _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. Decorator ~~~~~~~~~ The more straightforward way is by 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. .. 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 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 ` before writing your own: .. doctest:: >>> @attr.s ... class C(object): ... x = attr.ib(validator=attr.validators.instance_of(int)) >>> C(42) C(x=42) >>> C("42") Traceback (most recent call last): ... TypeError: ("'x' must be (got '42' that is a ).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=>, type=None), , '42') Of course you can mix and match the two approaches at your convenience: .. 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 (got '128' that is a ).", Attribute(name='x', default=NOTHING, validator=[>, ], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=one), , '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 (got '128' that is a ).", Attribute(name='x', default=NOTHING, validator=[>, ], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=None), , '128') 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 Converters are run *before* validators, so you can use validators to check the final form of the value. .. doctest:: >>> def validate_x(instance, attribute, value): ... if value < 0: ... raise ValueError("x must be be at least 0.") >>> @attr.s ... class C(object): ... x = attr.ib(converter=int, validator=validate_x) >>> o = C("0") >>> o.x 0 >>> C("-1") Traceback (most recent call last): ... ValueError: x must be be at least 0. .. _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 `. 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 `_-annotations: .. doctest:: >>> @attr.s ... class C: ... x = attr.ib(type=int) ... y: int = attr.ib() >>> attr.fields(C).x.type >>> attr.fields(C).y.type 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 >>> attr.fields(AutoC).foo.type >>> 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 .. 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 ----- By default, instances of classes have a dictionary for attribute storage. This wastes space for objects having very few data attributes. The space consumption can become significant when creating large numbers of instances. Normal Python classes can avoid using a separate dictionary for each instance of a class by `defining `_ ``__slots__``. For ``attrs`` classes it's enough to set ``slots=True``: .. doctest:: >>> @attr.s(slots=True) ... class Coordinates(object): ... x = attr.ib() ... y = attr.ib() .. note:: ``attrs`` slot classes can inherit from other classes just like non-slot classes, but some of the benefits of slot classes are lost if you do that. If you must inherit from other classes, try to inherit only from other slot classes. Slot classes are a little different than ordinary, dictionary-backed classes: - Assigning to a non-existent attribute of an instance will result in an ``AttributeError`` being raised. Depending on your needs, this might be a good thing since it will let you catch typos early. This is not the case if your class inherits from any non-slot classes. .. doctest:: >>> @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' - Since non-slot classes cannot be turned into slot classes after they have been created, ``attr.s(slots=True)`` will *replace* the class it is applied to with a copy. In almost all cases this isn't a problem, but we mention it for the sake of completeness. * One notable problem is that certain metaclass features like ``__init_subclass__`` do not work with slot classes. - Using :mod:`pickle` with slot 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__ ` and :meth:`__setstate__ ` methods yourself. Those methods are created for frozen slot classes because they won't pickle otherwise. `Think twice `_ before using :mod:`pickle` though. - As always with slot 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) All in all, setting ``slots=True`` is usually a very good idea. 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 ` 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 `_ 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') attrs-17.4.0/docs/extending.rst000066400000000000000000000066411322164444300164210ustar00rootroot00000000000000.. _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 `_ 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 `_ on top of it. An example for that is the package `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 `_ 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 >>> attr.fields(C).y.type 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] attrs-17.4.0/docs/how-does-it-work.rst000066400000000000000000000067251322164444300175560ustar00rootroot00000000000000.. _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 ``__slots__`` -- 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 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. To circumvent that ourselves in ``__init__``, ``attrs`` 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. **** Once constructed, frozen instances don't differ in any way from regular ones except that you cannot change its attributes. attrs-17.4.0/docs/index.rst000066400000000000000000000043051322164444300155360ustar00rootroot00000000000000====================================== ``attrs``: Classes Without Boilerplate ====================================== Release v\ |release| (:doc:`What's new? `). .. include:: ../README.rst :start-after: teaser-begin :end-before: -spiel-end- Getting Started =============== ``attrs`` is a Python-only package `hosted on PyPI `_. The recommended installation method is `pip `_-installing into a `virtualenv `_: .. 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 you need any help while getting started, feel free to use the ``python-attrs`` tag on `StackOverflow `_ 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. - ``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 api extending how-does-it-work Indices and tables ================== * :ref:`genindex` * :ref:`search` attrs-17.4.0/docs/license.rst000066400000000000000000000004731322164444300160530ustar00rootroot00000000000000=================== License and Credits =================== ``attrs`` is licensed under the `MIT `_ license. The full license text can be also found in the `source code repository `_. .. include:: ../AUTHORS.rst attrs-17.4.0/docs/overview.rst000066400000000000000000000071611322164444300163000ustar00rootroot00000000000000======== 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 ` 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. attrs-17.4.0/docs/why.rst000066400000000000000000000232141322164444300152360ustar00rootroot00000000000000.. _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 `_! …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__() ` 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__ `: ``[, , , ]``. 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 `_ 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 …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 all over again doesn't qualify for me. I usually manage to get some typos inside and there's simply more code that can break and thus has to be tested. To bring it into perspective, the equivalent of .. doctest:: >>> @attr.s ... class SmartClass(object): ... a = attr.ib() ... b = attr.ib() >>> SmartClass(1, 2) SmartClass(a=1, b=2) is .. doctest:: >>> class ArtisanalClass(object): ... def __init__(self, a, b): ... self.a = a ... self.b = b ... ... def __repr__(self): ... return "ArtisanalClass(a={}, b={})".format(self.a, self.b) ... ... def __eq__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) == (other.a, other.b) ... else: ... return NotImplemented ... ... def __ne__(self, other): ... result = self.__eq__(other) ... if result is NotImplemented: ... return NotImplemented ... else: ... return not result ... ... def __lt__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) < (other.a, other.b) ... else: ... return NotImplemented ... ... def __le__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) <= (other.a, other.b) ... else: ... return NotImplemented ... ... def __gt__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) > (other.a, other.b) ... else: ... return NotImplemented ... ... def __ge__(self, other): ... if other.__class__ is self.__class__: ... return (self.a, self.b) >= (other.a, other.b) ... else: ... return NotImplemented ... ... def __hash__(self): ... return hash((self.a, self.b)) >>> ArtisanalClass(a=1, b=2) ArtisanalClass(a=1, b=2) which is quite a mouthful and it doesn't even use any of ``attrs``'s more advanced features like validators or defaults values. Also: no tests whatsoever. And who will guarantee you, that you don't accidentally flip the ``<`` in your tenth implementation of ``__gt__``? 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 "" % (self.a,) >>> SmartClass(1, 2) .. 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. attrs-17.4.0/pyproject.toml000066400000000000000000000013611322164444300156600ustar00rootroot00000000000000[tool.towncrier] package = "attr" package_dir = "src" filename = "CHANGELOG.rst" template = "changelog.d/towncrier_template.rst" issue_format = "`#{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 attrs-17.4.0/setup.cfg000066400000000000000000000005441322164444300145670ustar00rootroot00000000000000[bdist_wheel] universal = 1 [metadata] # ensure LICENSE is included in wheel 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 attrs-17.4.0/setup.py000066400000000000000000000060601322164444300144570ustar00rootroot00000000000000import 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 :: 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, ) attrs-17.4.0/src/000077500000000000000000000000001322164444300135325ustar00rootroot00000000000000attrs-17.4.0/src/attr/000077500000000000000000000000001322164444300145045ustar00rootroot00000000000000attrs-17.4.0/src/attr/__init__.py000066400000000000000000000022101322164444300166100ustar00rootroot00000000000000from __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, make_class, validate ) __version__ = "17.4.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", "filters", "get_run_validators", "has", "ib", "make_class", "s", "set_run_validators", "validate", "validators", ] attrs-17.4.0/src/attr/_compat.py000066400000000000000000000103061322164444300165000ustar00rootroot00000000000000from __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 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(): # pragma: nocover """ Moved into a function for testability. """ try: import ctypes return ctypes except ImportError: return None 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: ctypes = import_ctypes() if ctypes is not None: set_closure_cell = ctypes.pythonapi.PyCell_Set set_closure_cell.argtypes = (ctypes.py_object, ctypes.py_object) set_closure_cell.restype = ctypes.c_int else: set_closure_cell = just_warn return set_closure_cell set_closure_cell = make_set_closure_cell() attrs-17.4.0/src/attr/_config.py000066400000000000000000000010021322164444300164530ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function __all__ = ["set_run_validators", "get_run_validators"] _run_validators = True def set_run_validators(run): """ Set whether or not validators are run. By default, they are run. """ if not isinstance(run, bool): raise TypeError("'run' must be bool.") global _run_validators _run_validators = run def get_run_validators(): """ Return whether or not validators are run. """ return _run_validators attrs-17.4.0/src/attr/_funcs.py000066400000000000000000000173261322164444300163440ustar00rootroot00000000000000from __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) attrs-17.4.0/src/attr/_make.py000066400000000000000000001402131322164444300161330ustar00rootroot00000000000000from __future__ import absolute_import, division, print_function import hashlib import linecache import sys import warnings from operator import itemgetter from . import _config from ._compat import PY2, isclass, iteritems, metadata_proxy, set_closure_cell from .exceptions import ( DefaultAlreadySetError, FrozenInstanceError, NotAnAttrsClassError, UnannotatedAttributeError ) # This is used at least twice, so cache it here. _obj_setattr = object.__setattr__ _init_converter_pat = "__attr_converter_{}" _init_factory_pat = "__attr_factory_{}" _tuple_property_pat = " {attr_name} = property(itemgetter({index}))" _empty_metadata_singleton = metadata_proxy({}) class _Nothing(object): """ Sentinel class to indicate the lack of a value when ``None`` is ambiguous. All instances of `_Nothing` are equal. """ def __copy__(self): return self def __deepcopy__(self, _): return self def __eq__(self, other): return other.__class__ == _Nothing def __ne__(self, other): return not self == other def __repr__(self): return "NOTHING" def __hash__(self): return 0xdeadbeef NOTHING = _Nothing() """ Sentinel to indicate the lack of a value when ``None`` is ambiguous. """ def attrib(default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, convert=None, metadata=None, type=None, converter=None): """ Create a new attribute on a class. .. warning:: Does *not* do anything unless the class is also decorated with :func:`attr.s`! :param default: A value that is used if an ``attrs``-generated ``__init__`` is used and no value is passed while instantiating or the attribute is excluded using ``init=False``. If the value is an instance of :class:`Factory`, its callable will be used to construct a new value (useful for mutable data types like lists or dicts). If a default is not set (or set manually to ``attr.NOTHING``), a value *must* be supplied when instantiating; otherwise a :exc:`TypeError` will be raised. The default can also be set using decorator notation as shown below. :type default: Any value. :param validator: :func:`callable` that is called by ``attrs``-generated ``__init__`` methods after the instance has been initialized. They receive the initialized instance, the :class:`Attribute`, and the passed value. The return value is *not* inspected so the validator has to throw an exception itself. If a ``list`` is passed, its items are treated as validators and must all pass. Validators can be globally disabled and re-enabled using :func:`get_run_validators`. The validator can also be set using decorator notation as shown below. :type validator: ``callable`` or a ``list`` of ``callable``\ s. :param bool repr: Include this attribute in the generated ``__repr__`` method. :param bool cmp: Include this attribute in the generated comparison methods (``__eq__`` et al). :param hash: Include this attribute in the generated ``__hash__`` method. If ``None`` (default), mirror *cmp*'s value. This is the correct behavior according the Python spec. Setting this value to anything else than ``None`` is *discouraged*. :type hash: ``bool`` or ``None`` :param bool init: Include this attribute in the generated ``__init__`` method. It is possible to set this to ``False`` and set a default value. In that case this attributed is unconditionally initialized with the specified default value or factory. :param callable converter: :func:`callable` that is called by ``attrs``-generated ``__init__`` methods to converter attribute's value to the desired format. It is given the passed-in value, and the returned value will be used as the new value of the attribute. The value is converted before being passed to the validator, if any. :param metadata: An arbitrary mapping, to be used by third-party components. See :ref:`extending_metadata`. :param type: The type of the attribute. In Python 3.6 or greater, the preferred method to specify the type is using a variable annotation (see `PEP 526 `_). This argument is provided for backward compatibility. Regardless of the approach used, the type will be stored on ``Attribute.type``. .. versionadded:: 15.2.0 *convert* .. versionadded:: 16.3.0 *metadata* .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. .. versionchanged:: 17.1.0 *hash* is ``None`` and therefore mirrors *cmp* by default. .. versionadded:: 17.3.0 *type* .. deprecated:: 17.4.0 *convert* .. versionadded:: 17.4.0 *converter* as a replacement for the deprecated *convert* to achieve consistency with other noun-based arguments. """ if hash is not None and hash is not True and hash is not False: raise TypeError( "Invalid value for hash. Must be True, False, or None." ) if convert is not None: if converter is not None: raise RuntimeError( "Can't pass both `convert` and `converter`. " "Please use `converter` only." ) warnings.warn( "The `convert` argument is deprecated in favor of `converter`. " "It will be removed after 2019/01.", DeprecationWarning, stacklevel=2 ) converter = convert if metadata is None: metadata = {} return _CountingAttr( default=default, validator=validator, repr=repr, cmp=cmp, hash=hash, init=init, converter=converter, metadata=metadata, type=type, ) def _make_attr_tuple_class(cls_name, attr_names): """ Create a tuple subclass to hold `Attribute`s for an `attrs` class. The subclass is a bare tuple with properties for names. class MyClassAttributes(tuple): __slots__ = () x = property(itemgetter(0)) """ attr_class_name = "{}Attributes".format(cls_name) attr_class_template = [ "class {}(tuple):".format(attr_class_name), " __slots__ = ()", ] if attr_names: for i, attr_name in enumerate(attr_names): attr_class_template.append(_tuple_property_pat.format( index=i, attr_name=attr_name, )) else: attr_class_template.append(" pass") globs = {"itemgetter": itemgetter} eval(compile("\n".join(attr_class_template), "", "exec"), globs) return globs[attr_class_name] # Tuple class for extracted attributes from a class definition. # `super_attrs` is a subset of `attrs`. _Attributes = _make_attr_tuple_class("_Attributes", [ "attrs", # all attributes to build dunder methods for "super_attrs", # attributes that have been inherited from super classes ]) def _is_class_var(annot): """ Check whether *annot* is a typing.ClassVar. The implementation is gross but importing `typing` is slow and there are discussions to remove it from the stdlib alltogether. """ return str(annot).startswith("typing.ClassVar") def _get_annotations(cls): """ Get annotations for *cls*. """ anns = getattr(cls, "__annotations__", None) if anns is None: return {} # Verify that the annotations aren't merely inherited. for super_cls in cls.__mro__[1:]: if anns is getattr(super_cls, "__annotations__", None): return {} return anns def _transform_attrs(cls, these, auto_attribs): """ Transform all `_CountingAttr`s on a class into `Attribute`s. If *these* is passed, use that and don't look for them on the class. Return an `_Attributes`. """ cd = cls.__dict__ anns = _get_annotations(cls) if these is not None: ca_list = sorted(( (name, ca) for name, ca in iteritems(these) ), key=lambda e: e[1].counter) elif auto_attribs is True: ca_names = { name for name, attr in cd.items() if isinstance(attr, _CountingAttr) } ca_list = [] annot_names = set() for attr_name, type in anns.items(): if _is_class_var(type): continue annot_names.add(attr_name) a = cd.get(attr_name, NOTHING) if not isinstance(a, _CountingAttr): if a is NOTHING: a = attrib() else: a = attrib(default=a) ca_list.append((attr_name, a)) unannotated = ca_names - annot_names if len(unannotated) > 0: raise UnannotatedAttributeError( "The following `attr.ib`s lack a type annotation: " + ", ".join(sorted( unannotated, key=lambda n: cd.get(n).counter )) + "." ) else: ca_list = sorted(( (name, attr) for name, attr in cd.items() if isinstance(attr, _CountingAttr) ), key=lambda e: e[1].counter) own_attrs = [ Attribute.from_counting_attr( name=attr_name, ca=ca, type=anns.get(attr_name), ) for attr_name, ca in ca_list ] super_attrs = [] taken_attr_names = {a.name: a for a in own_attrs} # Traverse the MRO and collect attributes. for super_cls in cls.__mro__[1:-1]: sub_attrs = getattr(super_cls, "__attrs_attrs__", None) if sub_attrs is not None: for a in sub_attrs: prev_a = taken_attr_names.get(a.name) # Only add an attribute if it hasn't been defined before. This # allows for overwriting attribute definitions by subclassing. if prev_a is None: super_attrs.append(a) taken_attr_names[a.name] = a attr_names = [a.name for a in super_attrs + own_attrs] AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) attrs = AttrsClass( super_attrs + [ Attribute.from_counting_attr( name=attr_name, ca=ca, type=anns.get(attr_name) ) for attr_name, ca in ca_list ] ) had_default = False for a in attrs: if had_default is True and a.default is NOTHING and a.init is True: raise ValueError( "No mandatory attributes allowed after an attribute with a " "default value or factory. Attribute in question: {a!r}" .format(a=a) ) elif had_default is False and \ a.default is not NOTHING and \ a.init is not False: had_default = True return _Attributes((attrs, super_attrs)) def _frozen_setattrs(self, name, value): """ Attached to frozen classes as __setattr__. """ raise FrozenInstanceError() def _frozen_delattrs(self, name): """ Attached to frozen classes as __delattr__. """ raise FrozenInstanceError() class _ClassBuilder(object): """ Iteratively build *one* class. """ __slots__ = ( "_cls", "_cls_dict", "_attrs", "_super_names", "_attr_names", "_slots", "_frozen", "_has_post_init", ) def __init__(self, cls, these, slots, frozen, auto_attribs): attrs, super_attrs = _transform_attrs(cls, these, auto_attribs) self._cls = cls self._cls_dict = dict(cls.__dict__) if slots else {} self._attrs = attrs self._super_names = set(a.name for a in super_attrs) self._attr_names = tuple(a.name for a in attrs) self._slots = slots self._frozen = frozen or _has_frozen_superclass(cls) self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) self._cls_dict["__attrs_attrs__"] = self._attrs if frozen: self._cls_dict["__setattr__"] = _frozen_setattrs self._cls_dict["__delattr__"] = _frozen_delattrs def __repr__(self): return "<_ClassBuilder(cls={cls})>".format(cls=self._cls.__name__) def build_class(self): """ Finalize class based on the accumulated configuration. Builder cannot be used anymore after calling this method. """ if self._slots is True: return self._create_slots_class() else: return self._patch_original_class() def _patch_original_class(self): """ Apply accumulated methods and return the class. """ cls = self._cls super_names = self._super_names # Clean class of attribute definitions (`attr.ib()`s). for name in self._attr_names: if name not in super_names and \ getattr(cls, name, None) is not None: delattr(cls, name) # Attach our dunder methods. for name, value in self._cls_dict.items(): setattr(cls, name, value) return cls def _create_slots_class(self): """ Build and return a new class with a `__slots__` attribute. """ super_names = self._super_names cd = { k: v for k, v in iteritems(self._cls_dict) if k not in tuple(self._attr_names) + ("__dict__",) } # We only add the names of attributes that aren't inherited. # Settings __slots__ to inherited attributes wastes memory. cd["__slots__"] = tuple( name for name in self._attr_names if name not in super_names ) qualname = getattr(self._cls, "__qualname__", None) if qualname is not None: cd["__qualname__"] = qualname attr_names = tuple(self._attr_names) def slots_getstate(self): """ Automatically created by attrs. """ return tuple(getattr(self, name) for name in attr_names) def slots_setstate(self, state): """ Automatically created by attrs. """ __bound_setattr = _obj_setattr.__get__(self, Attribute) for name, value in zip(attr_names, state): __bound_setattr(name, value) # slots and frozen require __getstate__/__setstate__ to work cd["__getstate__"] = slots_getstate cd["__setstate__"] = slots_setstate # Create new class based on old class and our methods. cls = type(self._cls)( self._cls.__name__, self._cls.__bases__, cd, ) # The following is a fix for # https://github.com/python-attrs/attrs/issues/102. On Python 3, # if a method mentions `__class__` or uses the no-arg super(), the # compiler will bake a reference to the class in the method itself # as `method.__closure__`. Since we replace the class with a # clone, we rewrite these references so it keeps working. for item in cls.__dict__.values(): if isinstance(item, (classmethod, staticmethod)): # Class- and staticmethods hide their functions inside. # These might need to be rewritten as well. closure_cells = getattr(item.__func__, "__closure__", None) else: closure_cells = getattr(item, "__closure__", None) if not closure_cells: # Catch None or the empty list. continue for cell in closure_cells: if cell.cell_contents is self._cls: set_closure_cell(cell, cls) return cls def add_repr(self, ns): self._cls_dict["__repr__"] = self._add_method_dunders( _make_repr(self._attrs, ns=ns) ) return self def add_str(self): repr = self._cls_dict.get("__repr__") if repr is None: raise ValueError( "__str__ can only be generated if a __repr__ exists." ) def __str__(self): return self.__repr__() self._cls_dict["__str__"] = self._add_method_dunders(__str__) return self def make_unhashable(self): self._cls_dict["__hash__"] = None return self def add_hash(self): self._cls_dict["__hash__"] = self._add_method_dunders( _make_hash(self._attrs) ) return self def add_init(self): self._cls_dict["__init__"] = self._add_method_dunders( _make_init( self._attrs, self._has_post_init, self._frozen, ) ) return self def add_cmp(self): cd = self._cls_dict cd["__eq__"], cd["__ne__"], cd["__lt__"], cd["__le__"], cd["__gt__"], \ cd["__ge__"] = ( self._add_method_dunders(meth) for meth in _make_cmp(self._attrs) ) return self def _add_method_dunders(self, method): """ Add __module__ and __qualname__ to a *method* if possible. """ try: method.__module__ = self._cls.__module__ except AttributeError: pass try: method.__qualname__ = ".".join( (self._cls.__qualname__, method.__name__,) ) except AttributeError: pass return method def attrs(maybe_cls=None, these=None, repr_ns=None, repr=True, cmp=True, hash=None, init=True, slots=False, frozen=False, str=False, auto_attribs=False): r""" A class decorator that adds `dunder `_\ -methods according to the specified attributes using :func:`attr.ib` or the *these* argument. :param these: A dictionary of name to :func:`attr.ib` mappings. This is useful to avoid the definition of your attributes within the class body because you can't (e.g. if you want to add ``__repr__`` methods to Django models) or don't want to. If *these* is not ``None``, ``attrs`` will *not* search the class body for attributes. :type these: :class:`dict` of :class:`str` to :func:`attr.ib` :param str repr_ns: When using nested classes, there's no way in Python 2 to automatically detect that. Therefore it's possible to set the namespace explicitly for a more meaningful ``repr`` output. :param bool repr: Create a ``__repr__`` method with a human readable representation of ``attrs`` attributes.. :param bool str: Create a ``__str__`` method that is identical to ``__repr__``. This is usually not necessary except for :class:`Exception`\ s. :param bool cmp: Create ``__eq__``, ``__ne__``, ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` methods that compare the class as if it were a tuple of its ``attrs`` attributes. But the attributes are *only* compared, if the type of both classes is *identical*! :param hash: If ``None`` (default), the ``__hash__`` method is generated according how *cmp* and *frozen* are set. 1. If *both* are True, ``attrs`` will generate a ``__hash__`` for you. 2. If *cmp* is True and *frozen* is False, ``__hash__`` will be set to None, marking it unhashable (which it is). 3. If *cmp* is False, ``__hash__`` will be left untouched meaning the ``__hash__`` method of the superclass will be used (if superclass is ``object``, this means it will fall back to id-based hashing.). Although not recommended, you can decide for yourself and force ``attrs`` to create one (e.g. if the class is immutable even though you didn't freeze it programmatically) by passing ``True`` or not. Both of these cases are rather special and should be used carefully. See the `Python documentation \ `_ and the `GitHub issue that led to the default behavior \ `_ for more details. :type hash: ``bool`` or ``None`` :param bool init: Create a ``__init__`` method that initializes the ``attrs`` attributes. Leading underscores are stripped for the argument name. If a ``__attrs_post_init__`` method exists on the class, it will be called after the class is fully initialized. :param bool slots: Create a slots_-style class that's more memory-efficient. See :ref:`slots` for further ramifications. :param bool frozen: Make instances immutable after initialization. If someone attempts to modify a frozen instance, :exc:`attr.exceptions.FrozenInstanceError` is raised. Please note: 1. This is achieved by installing a custom ``__setattr__`` method on your class so you can't implement an own one. 2. True immutability is impossible in Python. 3. This *does* have a minor a runtime performance :ref:`impact ` when initializing new instances. In other words: ``__init__`` is slightly slower with ``frozen=True``. 4. If a class is frozen, you cannot modify ``self`` in ``__attrs_post_init__`` or a self-written ``__init__``. You can circumvent that limitation by using ``object.__setattr__(self, "attribute_name", value)``. .. _slots: https://docs.python.org/3/reference/datamodel.html#slots :param bool auto_attribs: If True, collect `PEP 526`_-annotated attributes (Python 3.6 and later only) from the class body. In this case, you **must** annotate every field. If ``attrs`` encounters a field that is set to an :func:`attr.ib` but lacks a type annotation, an :exc:`attr.exceptions.UnannotatedAttributeError` is raised. Use ``field_name: typing.Any = attr.ib(...)`` if you don't want to set a type. If you assign a value to those attributes (e.g. ``x: int = 42``), that value becomes the default value like if it were passed using ``attr.ib(default=42)``. Passing an instance of :class:`Factory` also works as expected. Attributes annotated as :data:`typing.ClassVar` are **ignored**. .. _`PEP 526`: https://www.python.org/dev/peps/pep-0526/ .. versionadded:: 16.0.0 *slots* .. versionadded:: 16.1.0 *frozen* .. versionadded:: 16.3.0 *str*, and support for ``__attrs_post_init__``. .. versionchanged:: 17.1.0 *hash* supports ``None`` as value which is also the default now. .. versionadded:: 17.3.0 *auto_attribs* """ def wrap(cls): if getattr(cls, "__class__", None) is None: raise TypeError("attrs only works with new-style classes.") builder = _ClassBuilder(cls, these, slots, frozen, auto_attribs) if repr is True: builder.add_repr(repr_ns) if str is True: builder.add_str() if cmp is True: builder.add_cmp() if hash is not True and hash is not False and hash is not None: # Can't use `hash in` because 1 == True for example. raise TypeError( "Invalid value for hash. Must be True, False, or None." ) elif hash is False or (hash is None and cmp is False): pass elif hash is True or (hash is None and cmp is True and frozen is True): builder.add_hash() else: builder.make_unhashable() if init is True: builder.add_init() return builder.build_class() # maybe_cls's type depends on the usage of the decorator. It's a class # if it's used as `@attrs` but ``None`` if used as `@attrs()`. if maybe_cls is None: return wrap else: return wrap(maybe_cls) _attrs = attrs """ Internal alias so we can use it in functions that take an argument called *attrs*. """ if PY2: def _has_frozen_superclass(cls): """ Check whether *cls* has a frozen ancestor by looking at its __setattr__. """ return ( getattr( cls.__setattr__, "__module__", None ) == _frozen_setattrs.__module__ and cls.__setattr__.__name__ == _frozen_setattrs.__name__ ) else: def _has_frozen_superclass(cls): """ Check whether *cls* has a frozen ancestor by looking at its __setattr__. """ return cls.__setattr__ == _frozen_setattrs def _attrs_to_tuple(obj, attrs): """ Create a tuple of all values of *obj*'s *attrs*. """ return tuple(getattr(obj, a.name) for a in attrs) def _make_hash(attrs): attrs = tuple( a for a in attrs if a.hash is True or (a.hash is None and a.cmp is True) ) # We cache the generated hash methods for the same kinds of attributes. sha1 = hashlib.sha1() sha1.update(repr(attrs).encode("utf-8")) unique_filename = "" % (sha1.hexdigest(),) type_hash = hash(unique_filename) lines = [ "def __hash__(self):", " return hash((", " %d," % (type_hash,), ] for a in attrs: lines.append(" self.%s," % (a.name)) lines.append(" ))") script = "\n".join(lines) globs = {} locs = {} bytecode = compile(script, unique_filename, "exec") eval(bytecode, globs, locs) # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename, ) return locs["__hash__"] def _add_hash(cls, attrs): """ Add a hash method to *cls*. """ cls.__hash__ = _make_hash(attrs) return cls def __ne__(self, other): """ Check equality and either forward a NotImplemented or return the result negated. """ result = self.__eq__(other) if result is NotImplemented: return NotImplemented return not result def _make_cmp(attrs): attrs = [a for a in attrs if a.cmp] # We cache the generated eq methods for the same kinds of attributes. sha1 = hashlib.sha1() sha1.update(repr(attrs).encode("utf-8")) unique_filename = "" % (sha1.hexdigest(),) lines = [ "def __eq__(self, other):", " if other.__class__ is not self.__class__:", " return NotImplemented", ] # We can't just do a big self.x = other.x and... clause due to # irregularities like nan == nan is false but (nan,) == (nan,) is true. if attrs: lines.append(" return (") others = [ " ) == (", ] for a in attrs: lines.append(" self.%s," % (a.name,)) others.append(" other.%s," % (a.name,)) lines += others + [" )"] else: lines.append(" return True") script = "\n".join(lines) globs = {} locs = {} bytecode = compile(script, unique_filename, "exec") eval(bytecode, globs, locs) # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename, ) eq = locs["__eq__"] ne = __ne__ def attrs_to_tuple(obj): """ Save us some typing. """ return _attrs_to_tuple(obj, attrs) def __lt__(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) < attrs_to_tuple(other) else: return NotImplemented def __le__(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) <= attrs_to_tuple(other) else: return NotImplemented def __gt__(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) > attrs_to_tuple(other) else: return NotImplemented def __ge__(self, other): """ Automatically created by attrs. """ if isinstance(other, self.__class__): return attrs_to_tuple(self) >= attrs_to_tuple(other) else: return NotImplemented return eq, ne, __lt__, __le__, __gt__, __ge__ def _add_cmp(cls, attrs=None): """ Add comparison methods to *cls*. """ if attrs is None: attrs = cls.__attrs_attrs__ cls.__eq__, cls.__ne__, cls.__lt__, cls.__le__, cls.__gt__, cls.__ge__ = \ _make_cmp(attrs) return cls def _make_repr(attrs, ns): """ Make a repr method for *attr_names* adding *ns* to the full name. """ attr_names = tuple( a.name for a in attrs if a.repr ) def __repr__(self): """ Automatically created by attrs. """ real_cls = self.__class__ if ns is None: qualname = getattr(real_cls, "__qualname__", None) if qualname is not None: class_name = qualname.rsplit(">.", 1)[-1] else: class_name = real_cls.__name__ else: class_name = ns + "." + real_cls.__name__ return "{0}({1})".format( class_name, ", ".join( name + "=" + repr(getattr(self, name, NOTHING)) for name in attr_names ) ) return __repr__ def _add_repr(cls, ns=None, attrs=None): """ Add a repr method to *cls*. """ if attrs is None: attrs = cls.__attrs_attrs__ cls.__repr__ = _make_repr(attrs, ns) return cls def _make_init(attrs, post_init, frozen): attrs = [ a for a in attrs if a.init or a.default is not NOTHING ] # We cache the generated init methods for the same kinds of attributes. sha1 = hashlib.sha1() sha1.update(repr(attrs).encode("utf-8")) unique_filename = "".format( sha1.hexdigest() ) script, globs = _attrs_to_init_script( attrs, frozen, post_init, ) locs = {} bytecode = compile(script, unique_filename, "exec") attr_dict = dict((a.name, a) for a in attrs) globs.update({ "NOTHING": NOTHING, "attr_dict": attr_dict, }) if frozen is True: # Save the lookup overhead in __init__ if we need to circumvent # immutability. globs["_cached_setattr"] = _obj_setattr eval(bytecode, globs, locs) # In order of debuggers like PDB being able to step through the code, # we add a fake linecache entry. linecache.cache[unique_filename] = ( len(script), None, script.splitlines(True), unique_filename, ) return locs["__init__"] def _add_init(cls, frozen): """ Add a __init__ method to *cls*. If *frozen* is True, make it immutable. """ cls.__init__ = _make_init( cls.__attrs_attrs__, getattr(cls, "__attrs_post_init__", False), frozen, ) return cls def fields(cls): """ Returns the tuple of ``attrs`` attributes for a class. The tuple also allows accessing the fields by their names (see below for examples). :param type cls: Class to introspect. :raise TypeError: If *cls* is not a class. :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs`` class. :rtype: tuple (with name accessors) of :class:`attr.Attribute` .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields by name. """ if not isclass(cls): raise TypeError("Passed object must be a class.") attrs = getattr(cls, "__attrs_attrs__", None) if attrs is None: raise NotAnAttrsClassError( "{cls!r} is not an attrs-decorated class.".format(cls=cls) ) return attrs def validate(inst): """ Validate all attributes on *inst* that have a validator. Leaves all exceptions through. :param inst: Instance of a class with ``attrs`` attributes. """ if _config._run_validators is False: return for a in fields(inst.__class__): v = a.validator if v is not None: v(inst, a, getattr(inst, a.name)) def _attrs_to_init_script(attrs, frozen, post_init): """ Return a script of an initializer for *attrs* and a dict of globals. The globals are expected by the generated script. If *frozen* is True, we cannot set the attributes directly so we use a cached ``object.__setattr__``. """ lines = [] if frozen is True: lines.append( # Circumvent the __setattr__ descriptor to save one lookup per # assignment. "_setattr = _cached_setattr.__get__(self, self.__class__)" ) def fmt_setter(attr_name, value_var): return "_setattr('%(attr_name)s', %(value_var)s)" % { "attr_name": attr_name, "value_var": value_var, } def fmt_setter_with_converter(attr_name, value_var): conv_name = _init_converter_pat.format(attr_name) return "_setattr('%(attr_name)s', %(conv)s(%(value_var)s))" % { "attr_name": attr_name, "value_var": value_var, "conv": conv_name, } else: def fmt_setter(attr_name, value): return "self.%(attr_name)s = %(value)s" % { "attr_name": attr_name, "value": value, } def fmt_setter_with_converter(attr_name, value_var): conv_name = _init_converter_pat.format(attr_name) return "self.%(attr_name)s = %(conv)s(%(value_var)s)" % { "attr_name": attr_name, "value_var": value_var, "conv": conv_name, } args = [] attrs_to_validate = [] # This is a dictionary of names to validator and converter callables. # Injecting this into __init__ globals lets us avoid lookups. names_for_globals = {} for a in attrs: if a.validator: attrs_to_validate.append(a) attr_name = a.name arg_name = a.name.lstrip("_") has_factory = isinstance(a.default, Factory) if has_factory and a.default.takes_self: maybe_self = "self" else: maybe_self = "" if a.init is False: if has_factory: init_factory_name = _init_factory_pat.format(a.name) if a.converter is not None: lines.append(fmt_setter_with_converter( attr_name, init_factory_name + "({0})".format(maybe_self))) conv_name = _init_converter_pat.format(a.name) names_for_globals[conv_name] = a.converter else: lines.append(fmt_setter( attr_name, init_factory_name + "({0})".format(maybe_self) )) names_for_globals[init_factory_name] = a.default.factory else: if a.converter is not None: lines.append(fmt_setter_with_converter( attr_name, "attr_dict['{attr_name}'].default" .format(attr_name=attr_name) )) conv_name = _init_converter_pat.format(a.name) names_for_globals[conv_name] = a.converter else: lines.append(fmt_setter( attr_name, "attr_dict['{attr_name}'].default" .format(attr_name=attr_name) )) elif a.default is not NOTHING and not has_factory: args.append( "{arg_name}=attr_dict['{attr_name}'].default".format( arg_name=arg_name, attr_name=attr_name, ) ) if a.converter is not None: lines.append(fmt_setter_with_converter(attr_name, arg_name)) names_for_globals[_init_converter_pat.format(a.name)] = ( a.converter ) else: lines.append(fmt_setter(attr_name, arg_name)) elif has_factory: args.append("{arg_name}=NOTHING".format(arg_name=arg_name)) lines.append("if {arg_name} is not NOTHING:" .format(arg_name=arg_name)) init_factory_name = _init_factory_pat.format(a.name) if a.converter is not None: lines.append(" " + fmt_setter_with_converter( attr_name, arg_name )) lines.append("else:") lines.append(" " + fmt_setter_with_converter( attr_name, init_factory_name + "({0})".format(maybe_self) )) names_for_globals[_init_converter_pat.format(a.name)] = ( a.converter ) else: lines.append(" " + fmt_setter(attr_name, arg_name)) lines.append("else:") lines.append(" " + fmt_setter( attr_name, init_factory_name + "({0})".format(maybe_self) )) names_for_globals[init_factory_name] = a.default.factory else: args.append(arg_name) if a.converter is not None: lines.append(fmt_setter_with_converter(attr_name, arg_name)) names_for_globals[_init_converter_pat.format(a.name)] = ( a.converter ) else: lines.append(fmt_setter(attr_name, arg_name)) if attrs_to_validate: # we can skip this if there are no validators. names_for_globals["_config"] = _config lines.append("if _config._run_validators is True:") for a in attrs_to_validate: val_name = "__attr_validator_{}".format(a.name) attr_name = "__attr_{}".format(a.name) lines.append(" {}(self, {}, self.{})".format( val_name, attr_name, a.name)) names_for_globals[val_name] = a.validator names_for_globals[attr_name] = a if post_init: lines.append("self.__attrs_post_init__()") return """\ def __init__(self, {args}): {lines} """.format( args=", ".join(args), lines="\n ".join(lines) if lines else "pass", ), names_for_globals class Attribute(object): """ *Read-only* representation of an attribute. :attribute name: The name of the attribute. Plus *all* arguments of :func:`attr.ib`. For the version history of the fields, see :func:`attr.ib`. """ __slots__ = ( "name", "default", "validator", "repr", "cmp", "hash", "init", "metadata", "type", "converter", ) def __init__(self, name, default, validator, repr, cmp, hash, init, convert=None, metadata=None, type=None, converter=None): # Cache this descriptor here to speed things up later. bound_setattr = _obj_setattr.__get__(self, Attribute) # Despite the big red warning, people *do* instantiate `Attribute` # themselves. if convert is not None: if converter is not None: raise RuntimeError( "Can't pass both `convert` and `converter`. " "Please use `converter` only." ) warnings.warn( "The `convert` argument is deprecated in favor of `converter`." " It will be removed after 2019/01.", DeprecationWarning, stacklevel=2 ) converter = convert bound_setattr("name", name) bound_setattr("default", default) bound_setattr("validator", validator) bound_setattr("repr", repr) bound_setattr("cmp", cmp) bound_setattr("hash", hash) bound_setattr("init", init) bound_setattr("converter", converter) bound_setattr("metadata", ( metadata_proxy(metadata) if metadata else _empty_metadata_singleton )) bound_setattr("type", type) def __setattr__(self, name, value): raise FrozenInstanceError() @property def convert(self): warnings.warn( "The `convert` attribute is deprecated in favor of `converter`. " "It will be removed after 2019/01.", DeprecationWarning, stacklevel=2, ) return self.converter @classmethod def from_counting_attr(cls, name, ca, type=None): # type holds the annotated value. deal with conflicts: if type is None: type = ca.type elif ca.type is not None: raise ValueError( "Type annotation and type argument cannot both be present" ) inst_dict = { k: getattr(ca, k) for k in Attribute.__slots__ if k not in ( "name", "validator", "default", "type", "convert", ) # exclude methods and deprecated alias } return cls( name=name, validator=ca._validator, default=ca._default, type=type, **inst_dict ) # Don't use _add_pickle since fields(Attribute) doesn't work def __getstate__(self): """ Play nice with pickle. """ return tuple(getattr(self, name) if name != "metadata" else dict(self.metadata) for name in self.__slots__) def __setstate__(self, state): """ Play nice with pickle. """ bound_setattr = _obj_setattr.__get__(self, Attribute) for name, value in zip(self.__slots__, state): if name != "metadata": bound_setattr(name, value) else: bound_setattr(name, metadata_proxy(value) if value else _empty_metadata_singleton) _a = [ Attribute(name=name, default=NOTHING, validator=None, repr=True, cmp=True, hash=(name != "metadata"), init=True) for name in Attribute.__slots__ if name != "convert" # XXX: remove once `convert` is gone ] Attribute = _add_hash( _add_cmp(_add_repr(Attribute, attrs=_a), attrs=_a), attrs=[a for a in _a if a.hash] ) class _CountingAttr(object): """ Intermediate representation of attributes that uses a counter to preserve the order in which the attributes have been defined. *Internal* data structure of the attrs library. Running into is most likely the result of a bug like a forgotten `@attr.s` decorator. """ __slots__ = ("counter", "_default", "repr", "cmp", "hash", "init", "metadata", "_validator", "converter", "type") __attrs_attrs__ = tuple( Attribute(name=name, default=NOTHING, validator=None, repr=True, cmp=True, hash=True, init=True) for name in ("counter", "_default", "repr", "cmp", "hash", "init",) ) + ( Attribute(name="metadata", default=None, validator=None, repr=True, cmp=True, hash=False, init=True), ) cls_counter = 0 def __init__(self, default, validator, repr, cmp, hash, init, converter, metadata, type): _CountingAttr.cls_counter += 1 self.counter = _CountingAttr.cls_counter self._default = default # If validator is a list/tuple, wrap it using helper validator. if validator and isinstance(validator, (list, tuple)): self._validator = and_(*validator) else: self._validator = validator self.repr = repr self.cmp = cmp self.hash = hash self.init = init self.converter = converter self.metadata = metadata self.type = type def validator(self, meth): """ Decorator that adds *meth* to the list of validators. Returns *meth* unchanged. .. versionadded:: 17.1.0 """ if self._validator is None: self._validator = meth else: self._validator = and_(self._validator, meth) return meth def default(self, meth): """ Decorator that allows to set the default for an attribute. Returns *meth* unchanged. :raises DefaultAlreadySetError: If default has been set before. .. versionadded:: 17.1.0 """ if self._default is not NOTHING: raise DefaultAlreadySetError() self._default = Factory(meth, takes_self=True) return meth _CountingAttr = _add_cmp(_add_repr(_CountingAttr)) @attrs(slots=True, init=False, hash=True) class Factory(object): """ Stores a factory callable. If passed as the default value to :func:`attr.ib`, the factory is used to generate a new value. :param callable factory: A callable that takes either none or exactly one mandatory positional argument depending on *takes_self*. :param bool takes_self: Pass the partially initialized instance that is being initialized as a positional argument. .. versionadded:: 17.1.0 *takes_self* """ factory = attrib() takes_self = attrib() def __init__(self, factory, takes_self=False): """ `Factory` is part of the default machinery so if we want a default value here, we have to implement it ourselves. """ self.factory = factory self.takes_self = takes_self def make_class(name, attrs, bases=(object,), **attributes_arguments): """ A quick way to create a new class called *name* with *attrs*. :param name: The name for the new class. :type name: str :param attrs: A list of names or a dictionary of mappings of names to attributes. :type attrs: :class:`list` or :class:`dict` :param tuple bases: Classes that the new class will subclass. :param attributes_arguments: Passed unmodified to :func:`attr.s`. :return: A new class with *attrs*. :rtype: type .. versionadded:: 17.1.0 *bases* """ if isinstance(attrs, dict): cls_dict = attrs elif isinstance(attrs, (list, tuple)): cls_dict = dict((a, attrib()) for a in attrs) else: raise TypeError("attrs argument must be a dict or a list.") post_init = cls_dict.pop("__attrs_post_init__", None) type_ = type( name, bases, {} if post_init is None else {"__attrs_post_init__": post_init} ) # For pickling to work, the __module__ variable needs to be set to the # frame where the class is created. Bypass this step in environments where # sys._getframe is not defined (Jython for example) or sys._getframe is not # defined for arguments greater than 0 (IronPython). try: type_.__module__ = sys._getframe(1).f_globals.get( "__name__", "__main__", ) except (AttributeError, ValueError): pass return _attrs(these=cls_dict, **attributes_arguments)(type_) # These are required by within this module so we define them here and merely # import into .validators. @attrs(slots=True, hash=True) class _AndValidator(object): """ Compose many validators to a single one. """ _validators = attrib() def __call__(self, inst, attr, value): for v in self._validators: v(inst, attr, value) def and_(*validators): """ A validator that composes multiple validators into one. When called on a value, it runs all wrapped validators. :param validators: Arbitrary number of validators. :type validators: callables .. versionadded:: 17.1.0 """ vals = [] for validator in validators: vals.extend( validator._validators if isinstance(validator, _AndValidator) else [validator] ) return _AndValidator(tuple(vals)) attrs-17.4.0/src/attr/converters.py000066400000000000000000000010231322164444300172440ustar00rootroot00000000000000""" 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 attrs-17.4.0/src/attr/exceptions.py000066400000000000000000000021211322164444300172330ustar00rootroot00000000000000from __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 """ attrs-17.4.0/src/attr/filters.py000066400000000000000000000021771322164444300165350ustar00rootroot00000000000000""" 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_ attrs-17.4.0/src/attr/validators.py000066400000000000000000000115401322164444300172270ustar00rootroot00000000000000""" 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 ( "" .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 ( "" .format(interface=self.interface) ) def provides(interface): """ A validator that raises a :exc:`TypeError` if the initializer is called with an object that does not provide the requested *interface* (checks are performed using ``interface.providedBy(value)`` (see `zope.interface `_). :param 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 ( "" .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 ( "" .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) attrs-17.4.0/tests/000077500000000000000000000000001322164444300141055ustar00rootroot00000000000000attrs-17.4.0/tests/__init__.py000066400000000000000000000000001322164444300162040ustar00rootroot00000000000000attrs-17.4.0/tests/test_annotations.py000066400000000000000000000102471322164444300200570ustar00rootroot00000000000000""" Tests for PEP-526 type annotations. Python 3.6+ only. """ import types import typing import pytest import attr 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 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 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)) @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 @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()) attrs-17.4.0/tests/test_config.py000066400000000000000000000022141322164444300167620ustar00rootroot00000000000000""" Tests for `attr._config`. """ from __future__ import absolute_import, division, print_function import pytest from attr import _config class TestConfig(object): def test_default(self): """ Run validators by default. """ assert True is _config._run_validators def test_set_run_validators(self): """ Sets `_run_validators`. """ _config.set_run_validators(False) assert False is _config._run_validators _config.set_run_validators(True) assert True is _config._run_validators def test_get_run_validators(self): """ Returns `_run_validators`. """ _config._run_validators = False assert _config._run_validators is _config.get_run_validators() _config._run_validators = True assert _config._run_validators is _config.get_run_validators() def test_wrong_type(self): """ Passing anything else than a boolean raises TypeError. """ with pytest.raises(TypeError) as e: _config.set_run_validators("False") assert "'run' must be bool." == e.value.args[0] attrs-17.4.0/tests/test_converters.py000066400000000000000000000013631322164444300177130ustar00rootroot00000000000000""" 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") attrs-17.4.0/tests/test_dark_magic.py000066400000000000000000000234121322164444300176010ustar00rootroot00000000000000""" 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()) attrs-17.4.0/tests/test_dunders.py000066400000000000000000000331561322164444300171720ustar00rootroot00000000000000""" 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_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() attrs-17.4.0/tests/test_filters.py000066400000000000000000000042351322164444300171720ustar00rootroot00000000000000""" 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 attrs-17.4.0/tests/test_funcs.py000066400000000000000000000414441322164444300166430ustar00rootroot00000000000000""" Tests for `attr._funcs`. """ from __future__ import absolute_import, division, print_function from collections import Mapping, OrderedDict, Sequence import pytest from hypothesis import strategies as st from hypothesis import HealthCheck, assume, given, settings 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 .utils 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 attrs-17.4.0/tests/test_init_subclass.py000066400000000000000000000017031322164444300203610ustar00rootroot00000000000000""" 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 attrs-17.4.0/tests/test_make.py000066400000000000000000000706531322164444300164460ustar00rootroot00000000000000""" Tests for `attr._make`. """ from __future__ import absolute_import, division, print_function import inspect import itertools import sys from operator import attrgetter import pytest from hypothesis import given from hypothesis.strategies import booleans, integers, lists, sampled_from, text import attr from attr import _config from attr._compat import PY2 from attr._make import ( Attribute, Factory, _AndValidator, _Attributes, _ClassBuilder, _CountingAttr, _transform_attrs, and_, fields, make_class, validate ) from attr.exceptions import DefaultAlreadySetError, NotAnAttrsClassError from .utils import ( gen_attr_names, list_of_attrs, simple_attr, simple_attrs, simple_attrs_with_metadata, simple_attrs_without_metadata, simple_classes ) attrs_st = simple_attrs.map(lambda c: Attribute.from_counting_attr("name", c)) class TestCountingAttr(object): """ Tests for `attr`. """ def test_returns_Attr(self): """ Returns an instance of _CountingAttr. """ a = attr.ib() assert isinstance(a, _CountingAttr) def test_validators_lists_to_wrapped_tuples(self): """ If a list is passed as validator, it's just converted to a tuple. """ def v1(_, __): pass def v2(_, __): pass a = attr.ib(validator=[v1, v2]) assert _AndValidator((v1, v2,)) == a._validator def test_validator_decorator_single(self): """ If _CountingAttr.validator is used as a decorator and there is no decorator set, the decorated method is used as the validator. """ a = attr.ib() @a.validator def v(): pass assert v == a._validator @pytest.mark.parametrize("wrap", [ lambda v: v, lambda v: [v], lambda v: and_(v) ]) def test_validator_decorator(self, wrap): """ If _CountingAttr.validator is used as a decorator and there is already a decorator set, the decorators are composed using `and_`. """ def v(_, __): pass a = attr.ib(validator=wrap(v)) @a.validator def v2(self, _, __): pass assert _AndValidator((v, v2,)) == a._validator def test_default_decorator_already_set(self): """ Raise DefaultAlreadySetError if the decorator is used after a default has been set. """ a = attr.ib(default=42) with pytest.raises(DefaultAlreadySetError): @a.default def f(self): pass def test_default_decorator_sets(self): """ Decorator wraps the method in a Factory with pass_self=True and sets the default. """ a = attr.ib() @a.default def f(self): pass assert Factory(f, True) == a._default class TestAttribute(object): """ Tests for `attr.Attribute`. """ def test_deprecated_convert_argument(self): """ Using *convert* raises a DeprecationWarning and sets the converter field. """ def conv(v): return v with pytest.warns(DeprecationWarning) as wi: a = Attribute( "a", True, True, True, True, True, True, convert=conv ) w = wi.pop() assert conv == a.converter assert ( "The `convert` argument is deprecated in favor of `converter`. " "It will be removed after 2019/01.", ) == w.message.args assert __file__ == w.filename def test_deprecated_convert_attribute(self): """ If Attribute.convert is accessed, a DeprecationWarning is raised. """ def conv(v): return v a = simple_attr("a", converter=conv) with pytest.warns(DeprecationWarning) as wi: convert = a.convert w = wi.pop() assert conv is convert is a.converter assert ( "The `convert` attribute is deprecated in favor of `converter`. " "It will be removed after 2019/01.", ) == w.message.args assert __file__ == w.filename def test_convert_converter(self): """ A TypeError is raised if both *convert* and *converter* are passed. """ with pytest.raises(RuntimeError) as ei: Attribute( "a", True, True, True, True, True, True, convert=lambda v: v, converter=lambda v: v, ) assert ( "Can't pass both `convert` and `converter`. " "Please use `converter` only.", ) == ei.value.args def make_tc(): class TransformC(object): z = attr.ib() y = attr.ib() x = attr.ib() a = 42 return TransformC class TestTransformAttrs(object): """ Tests for `_transform_attrs`. """ def test_no_modifications(self): """ Doesn't attach __attrs_attrs__ to the class anymore. """ C = make_tc() _transform_attrs(C, None, False) assert None is getattr(C, "__attrs_attrs__", None) def test_normal(self): """ Transforms every `_CountingAttr` and leaves others (a) be. """ C = make_tc() attrs, _, = _transform_attrs(C, None, False) assert ["z", "y", "x"] == [a.name for a in attrs] def test_empty(self): """ No attributes works as expected. """ @attr.s class C(object): pass assert _Attributes(((), [])) == _transform_attrs(C, None, False) def test_transforms_to_attribute(self): """ All `_CountingAttr`s are transformed into `Attribute`s. """ C = make_tc() attrs, super_attrs = _transform_attrs(C, None, False) assert [] == super_attrs assert 3 == len(attrs) assert all(isinstance(a, Attribute) for a in attrs) def test_conflicting_defaults(self): """ Raises `ValueError` if attributes with defaults are followed by mandatory attributes. """ class C(object): x = attr.ib(default=None) y = attr.ib() with pytest.raises(ValueError) as e: _transform_attrs(C, None, False) assert ( "No mandatory attributes allowed after an attribute with a " "default value or factory. Attribute in question: Attribute" "(name='y', default=NOTHING, validator=None, repr=True, " "cmp=True, hash=None, init=True, metadata=mappingproxy({}), " "type=None, converter=None)", ) == e.value.args def test_these(self): """ If these is passed, use it and ignore body and super classes. """ class Base(object): z = attr.ib() class C(Base): y = attr.ib() attrs, super_attrs = _transform_attrs(C, {"x": attr.ib()}, False) assert [] == super_attrs assert ( simple_attr("x"), ) == attrs def test_multiple_inheritance(self): """ Order of attributes doesn't get mixed up by multiple inheritance. See #285 """ @attr.s class A(object): a1 = attr.ib(default="a1") a2 = attr.ib(default="a2") @attr.s class B(A): b1 = attr.ib(default="b1") b2 = attr.ib(default="b2") @attr.s class C(B, A): c1 = attr.ib(default="c1") c2 = attr.ib(default="c2") @attr.s class D(A): d1 = attr.ib(default="d1") d2 = attr.ib(default="d2") @attr.s class E(C, D): e1 = attr.ib(default="e1") e2 = attr.ib(default="e2") assert ( "E(a1='a1', a2='a2', b1='b1', b2='b2', c1='c1', c2='c2', d1='d1', " "d2='d2', e1='e1', e2='e2')" ) == repr(E()) class TestAttributes(object): """ Tests for the `attrs`/`attr.s` class decorator. """ @pytest.mark.skipif(not PY2, reason="No old-style classes in Py3") def test_catches_old_style(self): """ Raises TypeError on old-style classes. """ with pytest.raises(TypeError) as e: @attr.s class C: pass assert ("attrs only works with new-style classes.",) == e.value.args def test_sets_attrs(self): """ Sets the `__attrs_attrs__` class attribute with a list of `Attribute`s. """ @attr.s class C(object): x = attr.ib() assert "x" == C.__attrs_attrs__[0].name assert all(isinstance(a, Attribute) for a in C.__attrs_attrs__) def test_empty(self): """ No attributes, no problems. """ @attr.s class C3(object): pass assert "C3()" == repr(C3()) assert C3() == C3() @given(attr=attrs_st, attr_name=sampled_from(Attribute.__slots__)) def test_immutable(self, attr, attr_name): """ Attribute instances are immutable. """ with pytest.raises(AttributeError): setattr(attr, attr_name, 1) @pytest.mark.parametrize("method_name", [ "__repr__", "__eq__", "__hash__", "__init__", ]) def test_adds_all_by_default(self, method_name): """ If no further arguments are supplied, all add_XXX functions except add_hash are applied. __hash__ is set to None. """ # Set the method name to a sentinel and check whether it has been # overwritten afterwards. sentinel = object() class C(object): x = attr.ib() setattr(C, method_name, sentinel) C = attr.s(C) meth = getattr(C, method_name) assert sentinel != meth if method_name == "__hash__": assert meth is None @pytest.mark.parametrize("arg_name, method_name", [ ("repr", "__repr__"), ("cmp", "__eq__"), ("hash", "__hash__"), ("init", "__init__"), ]) def test_respects_add_arguments(self, arg_name, method_name): """ If a certain `add_XXX` is `False`, `__XXX__` is not added to the class. """ # Set the method name to a sentinel and check whether it has been # overwritten afterwards. sentinel = object() am_args = { "repr": True, "cmp": True, "hash": True, "init": True } am_args[arg_name] = False class C(object): x = attr.ib() setattr(C, method_name, sentinel) C = attr.s(**am_args)(C) assert sentinel == getattr(C, method_name) @pytest.mark.skipif(PY2, reason="__qualname__ is PY3-only.") @given(slots_outer=booleans(), slots_inner=booleans()) def test_repr_qualname(self, slots_outer, slots_inner): """ On Python 3, the name in repr is the __qualname__. """ @attr.s(slots=slots_outer) class C(object): @attr.s(slots=slots_inner) class D(object): pass assert "C.D()" == repr(C.D()) assert "GC.D()" == repr(GC.D()) @given(slots_outer=booleans(), slots_inner=booleans()) def test_repr_fake_qualname(self, slots_outer, slots_inner): """ Setting repr_ns overrides a potentially guessed namespace. """ @attr.s(slots=slots_outer) class C(object): @attr.s(repr_ns="C", slots=slots_inner) class D(object): pass assert "C.D()" == repr(C.D()) @pytest.mark.skipif(PY2, reason="__qualname__ is PY3-only.") @given(slots_outer=booleans(), slots_inner=booleans()) def test_name_not_overridden(self, slots_outer, slots_inner): """ On Python 3, __name__ is different from __qualname__. """ @attr.s(slots=slots_outer) class C(object): @attr.s(slots=slots_inner) class D(object): pass assert C.D.__name__ == "D" assert C.D.__qualname__ == C.__qualname__ + ".D" @given(with_validation=booleans()) def test_post_init(self, with_validation, monkeypatch): """ Verify that __attrs_post_init__ gets called if defined. """ monkeypatch.setattr(_config, "_run_validators", with_validation) @attr.s class C(object): x = attr.ib() y = attr.ib() def __attrs_post_init__(self2): self2.z = self2.x + self2.y c = C(x=10, y=20) assert 30 == getattr(c, 'z', None) def test_types(self): """ Sets the `Attribute.type` attr from type argument. """ @attr.s class C(object): x = attr.ib(type=int) y = attr.ib(type=str) z = attr.ib() assert int is fields(C).x.type assert str is fields(C).y.type assert None is fields(C).z.type @pytest.mark.parametrize("slots", [True, False]) def test_clean_class(self, slots): """ Attribute definitions do not appear on the class body after @attr.s. """ @attr.s(slots=slots) class C(object): x = attr.ib() x = getattr(C, "x", None) assert not isinstance(x, _CountingAttr) @attr.s class GC(object): @attr.s class D(object): pass class TestMakeClass(object): """ Tests for `make_class`. """ @pytest.mark.parametrize("ls", [ list, tuple ]) def test_simple(self, ls): """ Passing a list of strings creates attributes with default args. """ C1 = make_class("C1", ls(["a", "b"])) @attr.s class C2(object): a = attr.ib() b = attr.ib() assert C1.__attrs_attrs__ == C2.__attrs_attrs__ def test_dict(self): """ Passing a dict of name: _CountingAttr creates an equivalent class. """ C1 = make_class("C1", { "a": attr.ib(default=42), "b": attr.ib(default=None), }) @attr.s class C2(object): a = attr.ib(default=42) b = attr.ib(default=None) assert C1.__attrs_attrs__ == C2.__attrs_attrs__ def test_attr_args(self): """ attributes_arguments are passed to attributes """ C = make_class("C", ["x"], repr=False) assert repr(C(1)).startswith(" 0 for cls_a, raw_a in zip(fields(C), list_of_attrs): assert cls_a.metadata != {} assert cls_a.metadata == raw_a.metadata def test_metadata(self): """ If metadata that is not None is passed, it is used. This is necessary for coverage because the previous test is hypothesis-based. """ md = {} a = attr.ib(metadata=md) assert md is a.metadata class TestClassBuilder(object): """ Tests for `_ClassBuilder`. """ def test_repr_str(self): """ Trying to add a `__str__` without having a `__repr__` raises a ValueError. """ with pytest.raises(ValueError) as ei: make_class("C", {}, repr=False, str=True) assert ( "__str__ can only be generated if a __repr__ exists.", ) == ei.value.args def test_repr(self): """ repr of builder itself makes sense. """ class C(object): pass b = _ClassBuilder(C, None, True, True, False) assert "<_ClassBuilder(cls=C)>" == repr(b) def test_returns_self(self): """ All methods return the builder for chaining. """ class C(object): x = attr.ib() b = _ClassBuilder(C, None, True, True, False) cls = b.add_cmp().add_hash().add_init().add_repr("ns").add_str() \ .build_class() assert "ns.C(x=1)" == repr(cls(1)) @pytest.mark.parametrize("meth_name", [ "__init__", "__hash__", "__repr__", "__str__", "__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", ]) def test_attaches_meta_dunders(self, meth_name): """ Generated methods have correct __module__, __name__, and __qualname__ attributes. """ @attr.s(hash=True, str=True) class C(object): def organic(self): pass meth = getattr(C, meth_name) assert meth_name == meth.__name__ assert C.organic.__module__ == meth.__module__ if not PY2: organic_prefix = C.organic.__qualname__.rsplit(".", 1)[0] assert organic_prefix + "." + meth_name == meth.__qualname__ def test_handles_missing_meta_on_class(self): """ If the class hasn't a __module__ or __qualname__, the method hasn't either. """ class C(object): pass b = _ClassBuilder( C, these=None, slots=False, frozen=False, auto_attribs=False, ) b._cls = {} # no __module__; no __qualname__ def fake_meth(self): pass fake_meth.__module__ = "42" fake_meth.__qualname__ = "23" rv = b._add_method_dunders(fake_meth) assert "42" == rv.__module__ == fake_meth.__module__ assert "23" == rv.__qualname__ == fake_meth.__qualname__ attrs-17.4.0/tests/test_slots.py000066400000000000000000000247001322164444300166650ustar00rootroot00000000000000""" 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 attrs-17.4.0/tests/test_validators.py000066400000000000000000000146611322164444300176760ustar00rootroot00000000000000""" Tests for `attr.validators`. """ from __future__ import absolute_import, division, print_function import pytest import zope.interface import attr from attr import validators as validator_module from attr import has 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 ( ">" .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 ( "" .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 ( (">]) or None>") .format(func=repr(always_pass), type=TYPE) ) == repr(v) else: assert ( ("> 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( ("") ) == 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__ attrs-17.4.0/tests/utils.py000066400000000000000000000171041322164444300156220ustar00rootroot00000000000000""" Common helper functions for tests. """ from __future__ import absolute_import, division, print_function import keyword import string from collections import OrderedDict from hypothesis import strategies as st import attr 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() 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], ). 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, average_size=3, 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 ) attrs-17.4.0/tox.ini000066400000000000000000000034021322164444300142550ustar00rootroot00000000000000[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 deps = .[tests] commands = python -m pytest {posargs} [testenv:py27] deps = .[tests] commands = coverage run --parallel -m pytest {posargs} [testenv:py36] deps = .[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 # Needs a full install so isort can determine own/foreign imports. deps = .[tests] flake8 flake8-isort commands = flake8 src tests setup.py conftest.py docs/conf.py [testenv:isort] basepython = python3.6 # Needs a full install so isort can determine own/foreign imports. deps = .[tests] isort commands = isort --recursive setup.py conftest.py src tests [testenv:docs] basepython = python3.6 setenv = PYTHONHASHSEED = 0 deps = .[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