backpack


Namebackpack JSON
Version 0.1 PyPI version JSON
download
home_pagehttps://github.com/sdispater/backpack
SummaryUseful utilities for Python.
upload_time2016-08-04 21:11:21
maintainerNone
docs_urlNone
authorSébastien Eustace
requires_pythonNone
licenseMIT
keywords
VCS
bugtrack_url
requirements simplejson
Travis-CI
coveralls test coverage No coveralls.
            Backpack
########

.. image:: https://travis-ci.org/sdispater/backpack.png
   :alt: Backpack Build status
   :target: https://travis-ci.org/sdispater/backpack

Useful utilities for Python.

Supports Python **2.7+** and **3.2+**.


Collection
==========

The ``Collection`` class provides a fluent, convenient wrapper for working with list  of data.

To instantiatte a ``Collection`` you can also use the ``collection()`` helper.


Available Methods
*****************

For the remainder of this documentation, we'll discuss each method available on the ``Collection`` class.
Remember, all of these methods may be chained for fluently manipulating the underlying list or dict.
Furthermore, almost every method returns a new ``Collection`` instance,
allowing you to preserve the original copy of the collection when necessary.

You may select any method from this table to see an example of its usage:

* all_
* avg_
* chunk_
* collapse_
* contains_
* count_
* diff_
* each_
* every_
* filter_
* first_
* flatten_
* forget_
* for_page_
* get_
* implode_
* is_empty_
* last_
* map_
* merge_
* pluck_
* pop_
* prepend_
* pull_
* push_
* put_
* reduce_
* reject_
* reverse_
* serialize_
* shift_
* sort_
* sum_
* take_
* to_json_
* transform_
* unique_
* where_
* zip_


Methods Listing
***************

.. _all:

``all()``
---------

The ``all`` method simply returns the underlying list represented by the collection:

.. code-block:: python

    Collection([1, 2, 3]).all()

    # [1, 2, 3]


.. _avg:

``avg()``
---------

The ``avg`` method returns the average of all items in the collection:

.. code-block:: python

    Collection([1, 2, 3, 4, 5]).avg()

    # 3

If the collection contains nested objects or dictionaries, you must pass a key to use for determining
which values to calculate the average:

.. code-block:: python

    collection = Collection([
        {'name': 'JavaScript: The Good Parts', 'pages': 176},
        {'name': 'JavaScript: The Defnitive Guide', 'pages': 1096}
    ])

    collection.avg('pages')

    # 636


.. _chunk:

``chunk()``
-----------

The ``chunk`` method breaks the collection into multiple, smaller collections of a given size:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5, 6, 7])

    chunks = collection.chunk(4)

    chunks.serialize()

    # [[1, 2, 3, 4], [5, 6, 7]]


.. _collapse:

``collapse()``
--------------

The ``collapse`` method collapses a collection of lists into a flat collection:

.. code-block:: python

    collection = Collection([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

    collapsed = collection.collapse()

    collapsed.all()

    # [1, 2, 3, 4, 5, 6, 7, 8, 9]


.. _contains:

``contains()``
--------------

The ``contains`` method determines whether the collection contains a given item:

.. code-block:: python

    collection = Collection(['foo', 'bar'])

    collection.contains('foo')

    # True

You can also use the ``in`` keyword:

.. code-block:: python

    'foo' in collection

    # True

You can also pass a key / value pair to the ``contains`` method,
which will determine if the given pair exists in the collection:

.. code-block:: python

    collection = Collection([
        {'name': 'John', 'id': 1},
        {'name': 'Jane', 'id': 2}
    ])

    collection.contains('name', 'Simon')

    # False

Finally, you may also pass a callback to the ``contains`` method to perform your own truth test:


.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    collection.contains(lambda item: item > 5)

    # False


.. _count:

``count()``
-----------

The ``count`` method returns the total number of items in the collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    collection.count()

    # 4

The ``len`` function can also be used:

.. code-block:: python

    len(collection)

    # 4


.. _diff:

``diff()``
----------

The ``diff`` method compares the collection against another collection, a ``list`` or a ``dict``:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    diff = collection.diff([2, 4, 6, 8])

    diff.all()

    # [1, 3, 5]


.. _each:

``each()``
----------

The ``each`` method iterates over the items in the collection and passes each item to a given callback:

.. code-block:: python

    posts.each(lambda post: post.author().save(author))

Return ``False`` from your callback to break out of the loop:

.. code-block:: python

    posts.each(lambda post: post.author().save(author) if author.name == 'John' else False)


.. _every:

``every()``
-----------

The ``every`` method creates a new collection consisting of every n-th element:

.. code-block:: python

    collection = Collection(['a', 'b', 'c', 'd', 'e', 'f'])

    collection.every(4).all()

    # ['a', 'e']

You can optionally pass the offset as the second argument:


.. code-block:: python

    collection.every(4, 1).all()

    # ['b', 'f']


.. _filter:

``filter()``
------------

The ``filter`` method filters the collection by a given callback,
keeping only those items that pass a given truth test:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    filtered = collection.filter(lambda item: item > 2)

    filtered.all()

    # [3, 4]


.. _first:

``first()``
-----------

The ``first`` method returns the first element in the collection
that passes a given truth test:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    collection.first(lambda item: item > 2)

    # 3

You can also call the ``first`` method with no arguments
to get the first element in the collection.
If the collection is empty, ``None`` is returned:

.. code-block:: python

    collection.first()

    # 1


.. _flatten:

``flatten()``
-------------

The ``flatten`` method flattens a multi-dimensional collection into a single dimension:

.. code-block:: python

    collection = Collection([1, 2, [3, 4, 5, {'foo': 'bar'}]])

    flattened = collection.flatten()

    flattened.all()

    # [1, 2, 3, 4, 5, 'bar']


.. _forget:

``forget()``
------------

The ``forget`` method removes an item from the collection by its key:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    collection.forget(1)

    collection.all()

    # [1, 3, 4, 5]

.. warning::

    Unlike most other collection methods, ``forget`` does not return a new modified collection;
    it modifies the collection it is called on.


.. _for_page:

``for_page()``
--------------

The ``for_page`` method returns a new collection containing
the items that would be present on a given page number:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5, 6, 7, 8, 9])

    chunk = collection.for_page(2, 3)

    chunk.all()

    # 4, 5, 6

The method requires the page number and the number of items to show per page, respectively.


.. _get:

``get()``
---------

The ``get`` method returns the item at a given key. If the key does not exist, ``None`` is returned:

.. code-block:: python

    collection = Collection([1, 2, 3])

    collection.get(3)

    # None

You can optionally pass a default value as the second argument:

.. code-block:: python

    collection = Collection([1, 2, 3])

    collection.get(3, 'default-value')

    # default-value


.. _implode:

``implode()``
-------------

The ``implode`` method joins the items in a collection.
Its arguments depend on the type of items in the collection.

If the collection contains dictionaries or objects,
you must pass the key of the attributes you wish to join,
and the "glue" string you wish to place between the values:

.. code-block:: python

    collection = Collection([
        {'account_id': 1, 'product': 'Desk'},
        {'account_id': 2, 'product': 'Chair'}
    ])

    collection.implode('product', ', ')

    # Desk, Chair

If the collection contains simple strings,
simply pass the "glue" as the only argument to the method:

.. code-block:: python

    collection = Collection(['foo', 'bar', 'baz'])

    collection.implode('-')

    # foo-bar-baz


.. _is_empty:

``is_empty()``
--------------

The ``is_empty`` method returns ``True`` if the collection is empty; otherwise, ``False`` is returned:

.. code-block:: python

    Collection([]).is_empty()

    # True


.. _last:

``last()``
----------

The ``last`` method returns the last element in the collection that passes a given truth test:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    last = collection.last(lambda item: item < 3)

    # 2

You can also call the ``last`` method with no arguments to get the last element in the collection.
If the collection is empty, ``None`` is returned:

.. code-block:: python

    collection.last()

    # 4


.. _map:

``map()``
---------

The ``map`` method iterates through the collection and passes each value to the given callback.
The callback is free to modify the item and return it, thus forming a new collection of modified items:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    multiplied = collection.map(lambda item: item * 2)

    multiplied.all()

    # [2, 4, 6, 8]

.. warning::

    Like most other collection methods, ``map`` returns a new ``Collection`` instance;
    it does not modify the collection it is called on.
    If you want to transform the original collection, use the transform_ method.


.. _merge:

``merge()``
-----------

The merge method merges the given list into the collection:

.. code-block:: python

    collection = Collection(['Desk', 'Chair'])

    collection.merge(['Bookcase', 'Door'])

    collection.all()

    # ['Desk', 'Chair', 'Bookcase', 'Door']

.. warning::

    Unlike most other collection methods, ``merge`` does not return a new modified collection;
    it modifies the collection it is called on.


.. _pluck:

``pluck()``
-----------

The ``pluck`` method retrieves all of the collection values for a given key:

.. code-block:: python

    collection = Collection([
        {'product_id': 1, 'product': 'Desk'},
        {'product_id': 2, 'product': 'Chair'}
    ])

    plucked = collection.pluck('product')

    plucked.all()

    # ['Desk', 'Chair']

You can also specify how you wish the resulting collection to be keyed:

.. code-block:: python

    plucked = collection.pluck('name', 'product_id')

    plucked

    # {1: 'Desk', 2: 'Chair'}


.. _pop:

``pop()``
---------

The ``pop`` method removes and returns the last item from the collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    collection.pop()

    # 5

    collection.all()

    # [1, 2, 3, 4]


.. _prepend:

``prepend()``
-------------

The ``prepend`` method adds an item to the beginning of the collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    collection.prepend(0)

    collection.all()

    # [0, 1, 2, 3, 4]


.. _pull:

``pull()``
----------

The ``pull`` method removes and returns an item from the collection by its key:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    collection.pull(1)

    collection.all()

    # [1, 3, 4]


.. _push:

``push()``/``append()``
-----------------------

The ``push`` (or ``append``) method appends an item to the end of the collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    collection.push(5)

    collection.all()

    # [1, 2, 3, 4, 5]


.. _put:

``put()``
---------

The ``put`` method sets the given key and value in the collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    collection.put(1, 5)

    collection.all()

    # [1, 5, 3, 4]

.. note::

    It is equivalent to:

    .. code-block:: python

        collection[1] = 5


.. _reduce:

``reduce()``
------------

The ``reduce`` method reduces the collection to a single value,
passing the result of each iteration into the subsequent iteration:

.. code-block:: python

    collection = Collection([1, 2, 3])

    collection.reduce(lambda result, item: (result or 0) + item)

    # 6

The value for ``result`` on the first iteration is ``None``;
however, you can specify its initial value by passing a second argument to reduce:

.. code-block:: python

    collection.reduce(lambda result, item: result + item, 4)

    # 10


.. _reject:

``reject()``
------------

The ``reject`` method filters the collection using the given callback.
The callback should return ``True`` for any items it wishes to remove from the resulting collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4])

    filtered = collection.reject(lambda item: item > 2)

    filtered.all()

    # [1, 2]

For the inverse of ``reject``, see the filter_ method.


.. _reverse:

``reverse()``
-------------

The ``reverse`` method reverses the order of the collection's items:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    reverse = collection.reverse()

    reverse.all()

    # [5, 4, 3, 2, 1]


.. _serialize:

``serialize()``
---------------

The ``serialize`` method converts the collection into a ``list``.
If the collection's values are :ref:`ORM` models, the models will also be converted to dictionaries:

.. code-block:: python

    collection = Collection([User.find(1)])

    collection.serialize()

    # [{'id': 1, 'name': 'John'}]

.. warning::

    ``serialize`` also converts all of its nested objects.
    If you want to get the underlying items as is, use the all_ method instead.


.. _shift:

``shift()``
-----------

The ``shift`` method removes and returns the first item from the collection:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    collection.shift()

    # 1

    collection.all()

    # [2, 3, 4, 5]


.. _sort:

``sort()``
----------

The ``sort`` method sorts the collection:

.. code-block:: python

    collection = Collection([5, 3, 1, 2, 4])

    sorted = collection.sort()

    sorted.all()

    # [1, 2, 3, 4, 5]


.. _sum:

``sum()``
---------

The ``sum`` method returns the sum of all items in the collection:

.. code-block:: python

    Collection([1, 2, 3, 4, 5]).sum()

    # 15

If the collection contains dictionaries or objects, you must pass a key to use for determining which values to sum:

.. code-block:: python

    collection = Collection([
        {'name': 'JavaScript: The Good Parts', 'pages': 176},
        {'name': 'JavaScript: The Defnitive Guide', 'pages': 1096}
    ])

    collection.sum('pages')

    # 1272

In addition, you can pass your own callback to determine which values of the collection to sum:

.. code-block:: python

    collection = Collection([
        {'name': 'Chair', 'colors': ['Black']},
        {'name': 'Desk', 'colors': ['Black', 'Mahogany']},
        {'name': 'Bookcase', 'colors': ['Red', 'Beige', 'Brown']}
    ])

    collection.sum(lambda product: len(product['colors']))

    # 6


.. _take:

``take()``
----------

The ``take`` method returns a new collection with the specified number of items:

.. code-block:: python

    collection = Collection([0, 1, 2, 3, 4, 5])

    chunk = collection.take(3)

    chunk.all()

    # [0, 1, 2]

You can also pass a negative integer to take the specified amount of items from the end of the collection:

.. code-block:: python

    chunk = collection.chunk(-2)

    chunk.all()

    # [4, 5]


.. _to_json:

``to_json()``
-------------

The ``to_json`` method converts the collection into JSON:

.. code-block:: python

    collection = Collection([{'name': 'Desk', 'price': 200}])

    collection.to_json()

    # '[{"name": "Desk", "price": 200}]'


.. _transform:

``transform()``
---------------

The ``transform`` method iterates over the collection and calls the given callback
with each item in the collection.
The items in the collection will be replaced by the values returned by the callback:

.. code-block:: python

    collection = Collection([1, 2, 3, 4, 5])

    collection.transform(lambda item: item * 2)

    collection.all()

    # [2, 4, 6, 8, 10]

.. warning::

    Unlike most other collection methods, ``transform`` modifies the collection itself.
    If you wish to create a new collection instead, use the map_ method.


.. _unique:

``unique()``
------------

The ``unique`` method returns all of the unique items in the collection:

.. code-block:: python

    collection = Collection([1, 1, 2, 2, 3, 4, 2])

    unique = collection.unique()

    unique.all()

    # [1, 2, 3, 4]

When dealing with dictionaries or objects, you can specify the key used to determine uniqueness:

.. code-block:: python

    collection = Collection([
        {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},
        {'name': 'iPhone 5', 'brand': 'Apple', 'type': 'phone'},
        {'name': 'Apple Watch', 'brand': 'Apple', 'type': 'watch'},
        {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'},
        {'name': 'Galaxy Gear', 'brand': 'Samsung', 'type': 'watch'}
    ])

    unique = collection.unique('brand')

    unique.all()

    # [
    #     {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},
    #     {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'}
    # ]

You can also pass your own callback to determine item uniqueness:

.. code-block:: python

    unique = collection.unique(lambda item: item['brand'] + item['type'])

    unique.all()

    # [
    #     {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},
    #     {'name': 'Apple Watch', 'brand': 'Apple', 'type': 'watch'},
    #     {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'},
    #     {'name': 'Galaxy Gear', 'brand': 'Samsung', 'type': 'watch'}
    # ]


.. _where:

``where()``
-----------

The ``where`` method filters the collection by a given key / value pair:

.. code-block:: python

    collection = Collection([
        {'name': 'Desk', 'price': 200},
        {'name': 'Chair', 'price': 100},
        {'name': 'Bookcase', 'price': 150},
        {'name': 'Door', 'price': 100},
    ])

    filtered = collection.where('price', 100)

    filtered.all()

    # [
    #     {'name': 'Chair', 'price': 100},
    #     {'name': 'Door', 'price': 100}
    # ]


.. _zip:

``zip()``
---------

The ``zip`` method merges together the values of the given list
with the values of the collection at the corresponding index:

.. code-block:: python

    collection = Collection(['Chair', 'Desk'])

    zipped = collection.zip([100, 200])

    zipped.all()

    # [('Chair', 100), ('Desk', 200)]
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/sdispater/backpack",
    "name": "backpack",
    "maintainer": null,
    "docs_url": null,
    "requires_python": null,
    "maintainer_email": null,
    "keywords": null,
    "author": "S\u00e9bastien Eustace",
    "author_email": "sebastien@eustace.io",
    "download_url": "https://files.pythonhosted.org/packages/4e/d1/cd2034b49a3bea4cdc368a96d9d11043c71e6c13056f61976da720d89884/backpack-0.1.tar.gz",
    "platform": "UNKNOWN",
    "description": "Backpack\n########\n\n.. image:: https://travis-ci.org/sdispater/backpack.png\n   :alt: Backpack Build status\n   :target: https://travis-ci.org/sdispater/backpack\n\nUseful utilities for Python.\n\nSupports Python **2.7+** and **3.2+**.\n\n\nCollection\n==========\n\nThe ``Collection`` class provides a fluent, convenient wrapper for working with list  of data.\n\nTo instantiatte a ``Collection`` you can also use the ``collection()`` helper.\n\n\nAvailable Methods\n*****************\n\nFor the remainder of this documentation, we'll discuss each method available on the ``Collection`` class.\nRemember, all of these methods may be chained for fluently manipulating the underlying list or dict.\nFurthermore, almost every method returns a new ``Collection`` instance,\nallowing you to preserve the original copy of the collection when necessary.\n\nYou may select any method from this table to see an example of its usage:\n\n* all_\n* avg_\n* chunk_\n* collapse_\n* contains_\n* count_\n* diff_\n* each_\n* every_\n* filter_\n* first_\n* flatten_\n* forget_\n* for_page_\n* get_\n* implode_\n* is_empty_\n* last_\n* map_\n* merge_\n* pluck_\n* pop_\n* prepend_\n* pull_\n* push_\n* put_\n* reduce_\n* reject_\n* reverse_\n* serialize_\n* shift_\n* sort_\n* sum_\n* take_\n* to_json_\n* transform_\n* unique_\n* where_\n* zip_\n\n\nMethods Listing\n***************\n\n.. _all:\n\n``all()``\n---------\n\nThe ``all`` method simply returns the underlying list represented by the collection:\n\n.. code-block:: python\n\n    Collection([1, 2, 3]).all()\n\n    # [1, 2, 3]\n\n\n.. _avg:\n\n``avg()``\n---------\n\nThe ``avg`` method returns the average of all items in the collection:\n\n.. code-block:: python\n\n    Collection([1, 2, 3, 4, 5]).avg()\n\n    # 3\n\nIf the collection contains nested objects or dictionaries, you must pass a key to use for determining\nwhich values to calculate the average:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'name': 'JavaScript: The Good Parts', 'pages': 176},\n        {'name': 'JavaScript: The Defnitive Guide', 'pages': 1096}\n    ])\n\n    collection.avg('pages')\n\n    # 636\n\n\n.. _chunk:\n\n``chunk()``\n-----------\n\nThe ``chunk`` method breaks the collection into multiple, smaller collections of a given size:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5, 6, 7])\n\n    chunks = collection.chunk(4)\n\n    chunks.serialize()\n\n    # [[1, 2, 3, 4], [5, 6, 7]]\n\n\n.. _collapse:\n\n``collapse()``\n--------------\n\nThe ``collapse`` method collapses a collection of lists into a flat collection:\n\n.. code-block:: python\n\n    collection = Collection([[1, 2, 3], [4, 5, 6], [7, 8, 9]])\n\n    collapsed = collection.collapse()\n\n    collapsed.all()\n\n    # [1, 2, 3, 4, 5, 6, 7, 8, 9]\n\n\n.. _contains:\n\n``contains()``\n--------------\n\nThe ``contains`` method determines whether the collection contains a given item:\n\n.. code-block:: python\n\n    collection = Collection(['foo', 'bar'])\n\n    collection.contains('foo')\n\n    # True\n\nYou can also use the ``in`` keyword:\n\n.. code-block:: python\n\n    'foo' in collection\n\n    # True\n\nYou can also pass a key / value pair to the ``contains`` method,\nwhich will determine if the given pair exists in the collection:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'name': 'John', 'id': 1},\n        {'name': 'Jane', 'id': 2}\n    ])\n\n    collection.contains('name', 'Simon')\n\n    # False\n\nFinally, you may also pass a callback to the ``contains`` method to perform your own truth test:\n\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    collection.contains(lambda item: item > 5)\n\n    # False\n\n\n.. _count:\n\n``count()``\n-----------\n\nThe ``count`` method returns the total number of items in the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    collection.count()\n\n    # 4\n\nThe ``len`` function can also be used:\n\n.. code-block:: python\n\n    len(collection)\n\n    # 4\n\n\n.. _diff:\n\n``diff()``\n----------\n\nThe ``diff`` method compares the collection against another collection, a ``list`` or a ``dict``:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    diff = collection.diff([2, 4, 6, 8])\n\n    diff.all()\n\n    # [1, 3, 5]\n\n\n.. _each:\n\n``each()``\n----------\n\nThe ``each`` method iterates over the items in the collection and passes each item to a given callback:\n\n.. code-block:: python\n\n    posts.each(lambda post: post.author().save(author))\n\nReturn ``False`` from your callback to break out of the loop:\n\n.. code-block:: python\n\n    posts.each(lambda post: post.author().save(author) if author.name == 'John' else False)\n\n\n.. _every:\n\n``every()``\n-----------\n\nThe ``every`` method creates a new collection consisting of every n-th element:\n\n.. code-block:: python\n\n    collection = Collection(['a', 'b', 'c', 'd', 'e', 'f'])\n\n    collection.every(4).all()\n\n    # ['a', 'e']\n\nYou can optionally pass the offset as the second argument:\n\n\n.. code-block:: python\n\n    collection.every(4, 1).all()\n\n    # ['b', 'f']\n\n\n.. _filter:\n\n``filter()``\n------------\n\nThe ``filter`` method filters the collection by a given callback,\nkeeping only those items that pass a given truth test:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    filtered = collection.filter(lambda item: item > 2)\n\n    filtered.all()\n\n    # [3, 4]\n\n\n.. _first:\n\n``first()``\n-----------\n\nThe ``first`` method returns the first element in the collection\nthat passes a given truth test:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    collection.first(lambda item: item > 2)\n\n    # 3\n\nYou can also call the ``first`` method with no arguments\nto get the first element in the collection.\nIf the collection is empty, ``None`` is returned:\n\n.. code-block:: python\n\n    collection.first()\n\n    # 1\n\n\n.. _flatten:\n\n``flatten()``\n-------------\n\nThe ``flatten`` method flattens a multi-dimensional collection into a single dimension:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, [3, 4, 5, {'foo': 'bar'}]])\n\n    flattened = collection.flatten()\n\n    flattened.all()\n\n    # [1, 2, 3, 4, 5, 'bar']\n\n\n.. _forget:\n\n``forget()``\n------------\n\nThe ``forget`` method removes an item from the collection by its key:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    collection.forget(1)\n\n    collection.all()\n\n    # [1, 3, 4, 5]\n\n.. warning::\n\n    Unlike most other collection methods, ``forget`` does not return a new modified collection;\n    it modifies the collection it is called on.\n\n\n.. _for_page:\n\n``for_page()``\n--------------\n\nThe ``for_page`` method returns a new collection containing\nthe items that would be present on a given page number:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5, 6, 7, 8, 9])\n\n    chunk = collection.for_page(2, 3)\n\n    chunk.all()\n\n    # 4, 5, 6\n\nThe method requires the page number and the number of items to show per page, respectively.\n\n\n.. _get:\n\n``get()``\n---------\n\nThe ``get`` method returns the item at a given key. If the key does not exist, ``None`` is returned:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3])\n\n    collection.get(3)\n\n    # None\n\nYou can optionally pass a default value as the second argument:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3])\n\n    collection.get(3, 'default-value')\n\n    # default-value\n\n\n.. _implode:\n\n``implode()``\n-------------\n\nThe ``implode`` method joins the items in a collection.\nIts arguments depend on the type of items in the collection.\n\nIf the collection contains dictionaries or objects,\nyou must pass the key of the attributes you wish to join,\nand the \"glue\" string you wish to place between the values:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'account_id': 1, 'product': 'Desk'},\n        {'account_id': 2, 'product': 'Chair'}\n    ])\n\n    collection.implode('product', ', ')\n\n    # Desk, Chair\n\nIf the collection contains simple strings,\nsimply pass the \"glue\" as the only argument to the method:\n\n.. code-block:: python\n\n    collection = Collection(['foo', 'bar', 'baz'])\n\n    collection.implode('-')\n\n    # foo-bar-baz\n\n\n.. _is_empty:\n\n``is_empty()``\n--------------\n\nThe ``is_empty`` method returns ``True`` if the collection is empty; otherwise, ``False`` is returned:\n\n.. code-block:: python\n\n    Collection([]).is_empty()\n\n    # True\n\n\n.. _last:\n\n``last()``\n----------\n\nThe ``last`` method returns the last element in the collection that passes a given truth test:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    last = collection.last(lambda item: item < 3)\n\n    # 2\n\nYou can also call the ``last`` method with no arguments to get the last element in the collection.\nIf the collection is empty, ``None`` is returned:\n\n.. code-block:: python\n\n    collection.last()\n\n    # 4\n\n\n.. _map:\n\n``map()``\n---------\n\nThe ``map`` method iterates through the collection and passes each value to the given callback.\nThe callback is free to modify the item and return it, thus forming a new collection of modified items:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    multiplied = collection.map(lambda item: item * 2)\n\n    multiplied.all()\n\n    # [2, 4, 6, 8]\n\n.. warning::\n\n    Like most other collection methods, ``map`` returns a new ``Collection`` instance;\n    it does not modify the collection it is called on.\n    If you want to transform the original collection, use the transform_ method.\n\n\n.. _merge:\n\n``merge()``\n-----------\n\nThe merge method merges the given list into the collection:\n\n.. code-block:: python\n\n    collection = Collection(['Desk', 'Chair'])\n\n    collection.merge(['Bookcase', 'Door'])\n\n    collection.all()\n\n    # ['Desk', 'Chair', 'Bookcase', 'Door']\n\n.. warning::\n\n    Unlike most other collection methods, ``merge`` does not return a new modified collection;\n    it modifies the collection it is called on.\n\n\n.. _pluck:\n\n``pluck()``\n-----------\n\nThe ``pluck`` method retrieves all of the collection values for a given key:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'product_id': 1, 'product': 'Desk'},\n        {'product_id': 2, 'product': 'Chair'}\n    ])\n\n    plucked = collection.pluck('product')\n\n    plucked.all()\n\n    # ['Desk', 'Chair']\n\nYou can also specify how you wish the resulting collection to be keyed:\n\n.. code-block:: python\n\n    plucked = collection.pluck('name', 'product_id')\n\n    plucked\n\n    # {1: 'Desk', 2: 'Chair'}\n\n\n.. _pop:\n\n``pop()``\n---------\n\nThe ``pop`` method removes and returns the last item from the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    collection.pop()\n\n    # 5\n\n    collection.all()\n\n    # [1, 2, 3, 4]\n\n\n.. _prepend:\n\n``prepend()``\n-------------\n\nThe ``prepend`` method adds an item to the beginning of the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    collection.prepend(0)\n\n    collection.all()\n\n    # [0, 1, 2, 3, 4]\n\n\n.. _pull:\n\n``pull()``\n----------\n\nThe ``pull`` method removes and returns an item from the collection by its key:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    collection.pull(1)\n\n    collection.all()\n\n    # [1, 3, 4]\n\n\n.. _push:\n\n``push()``/``append()``\n-----------------------\n\nThe ``push`` (or ``append``) method appends an item to the end of the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    collection.push(5)\n\n    collection.all()\n\n    # [1, 2, 3, 4, 5]\n\n\n.. _put:\n\n``put()``\n---------\n\nThe ``put`` method sets the given key and value in the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    collection.put(1, 5)\n\n    collection.all()\n\n    # [1, 5, 3, 4]\n\n.. note::\n\n    It is equivalent to:\n\n    .. code-block:: python\n\n        collection[1] = 5\n\n\n.. _reduce:\n\n``reduce()``\n------------\n\nThe ``reduce`` method reduces the collection to a single value,\npassing the result of each iteration into the subsequent iteration:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3])\n\n    collection.reduce(lambda result, item: (result or 0) + item)\n\n    # 6\n\nThe value for ``result`` on the first iteration is ``None``;\nhowever, you can specify its initial value by passing a second argument to reduce:\n\n.. code-block:: python\n\n    collection.reduce(lambda result, item: result + item, 4)\n\n    # 10\n\n\n.. _reject:\n\n``reject()``\n------------\n\nThe ``reject`` method filters the collection using the given callback.\nThe callback should return ``True`` for any items it wishes to remove from the resulting collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4])\n\n    filtered = collection.reject(lambda item: item > 2)\n\n    filtered.all()\n\n    # [1, 2]\n\nFor the inverse of ``reject``, see the filter_ method.\n\n\n.. _reverse:\n\n``reverse()``\n-------------\n\nThe ``reverse`` method reverses the order of the collection's items:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    reverse = collection.reverse()\n\n    reverse.all()\n\n    # [5, 4, 3, 2, 1]\n\n\n.. _serialize:\n\n``serialize()``\n---------------\n\nThe ``serialize`` method converts the collection into a ``list``.\nIf the collection's values are :ref:`ORM` models, the models will also be converted to dictionaries:\n\n.. code-block:: python\n\n    collection = Collection([User.find(1)])\n\n    collection.serialize()\n\n    # [{'id': 1, 'name': 'John'}]\n\n.. warning::\n\n    ``serialize`` also converts all of its nested objects.\n    If you want to get the underlying items as is, use the all_ method instead.\n\n\n.. _shift:\n\n``shift()``\n-----------\n\nThe ``shift`` method removes and returns the first item from the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    collection.shift()\n\n    # 1\n\n    collection.all()\n\n    # [2, 3, 4, 5]\n\n\n.. _sort:\n\n``sort()``\n----------\n\nThe ``sort`` method sorts the collection:\n\n.. code-block:: python\n\n    collection = Collection([5, 3, 1, 2, 4])\n\n    sorted = collection.sort()\n\n    sorted.all()\n\n    # [1, 2, 3, 4, 5]\n\n\n.. _sum:\n\n``sum()``\n---------\n\nThe ``sum`` method returns the sum of all items in the collection:\n\n.. code-block:: python\n\n    Collection([1, 2, 3, 4, 5]).sum()\n\n    # 15\n\nIf the collection contains dictionaries or objects, you must pass a key to use for determining which values to sum:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'name': 'JavaScript: The Good Parts', 'pages': 176},\n        {'name': 'JavaScript: The Defnitive Guide', 'pages': 1096}\n    ])\n\n    collection.sum('pages')\n\n    # 1272\n\nIn addition, you can pass your own callback to determine which values of the collection to sum:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'name': 'Chair', 'colors': ['Black']},\n        {'name': 'Desk', 'colors': ['Black', 'Mahogany']},\n        {'name': 'Bookcase', 'colors': ['Red', 'Beige', 'Brown']}\n    ])\n\n    collection.sum(lambda product: len(product['colors']))\n\n    # 6\n\n\n.. _take:\n\n``take()``\n----------\n\nThe ``take`` method returns a new collection with the specified number of items:\n\n.. code-block:: python\n\n    collection = Collection([0, 1, 2, 3, 4, 5])\n\n    chunk = collection.take(3)\n\n    chunk.all()\n\n    # [0, 1, 2]\n\nYou can also pass a negative integer to take the specified amount of items from the end of the collection:\n\n.. code-block:: python\n\n    chunk = collection.chunk(-2)\n\n    chunk.all()\n\n    # [4, 5]\n\n\n.. _to_json:\n\n``to_json()``\n-------------\n\nThe ``to_json`` method converts the collection into JSON:\n\n.. code-block:: python\n\n    collection = Collection([{'name': 'Desk', 'price': 200}])\n\n    collection.to_json()\n\n    # '[{\"name\": \"Desk\", \"price\": 200}]'\n\n\n.. _transform:\n\n``transform()``\n---------------\n\nThe ``transform`` method iterates over the collection and calls the given callback\nwith each item in the collection.\nThe items in the collection will be replaced by the values returned by the callback:\n\n.. code-block:: python\n\n    collection = Collection([1, 2, 3, 4, 5])\n\n    collection.transform(lambda item: item * 2)\n\n    collection.all()\n\n    # [2, 4, 6, 8, 10]\n\n.. warning::\n\n    Unlike most other collection methods, ``transform`` modifies the collection itself.\n    If you wish to create a new collection instead, use the map_ method.\n\n\n.. _unique:\n\n``unique()``\n------------\n\nThe ``unique`` method returns all of the unique items in the collection:\n\n.. code-block:: python\n\n    collection = Collection([1, 1, 2, 2, 3, 4, 2])\n\n    unique = collection.unique()\n\n    unique.all()\n\n    # [1, 2, 3, 4]\n\nWhen dealing with dictionaries or objects, you can specify the key used to determine uniqueness:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},\n        {'name': 'iPhone 5', 'brand': 'Apple', 'type': 'phone'},\n        {'name': 'Apple Watch', 'brand': 'Apple', 'type': 'watch'},\n        {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'},\n        {'name': 'Galaxy Gear', 'brand': 'Samsung', 'type': 'watch'}\n    ])\n\n    unique = collection.unique('brand')\n\n    unique.all()\n\n    # [\n    #     {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},\n    #     {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'}\n    # ]\n\nYou can also pass your own callback to determine item uniqueness:\n\n.. code-block:: python\n\n    unique = collection.unique(lambda item: item['brand'] + item['type'])\n\n    unique.all()\n\n    # [\n    #     {'name': 'iPhone 6', 'brand': 'Apple', 'type': 'phone'},\n    #     {'name': 'Apple Watch', 'brand': 'Apple', 'type': 'watch'},\n    #     {'name': 'Galaxy S6', 'brand': 'Samsung', 'type': 'phone'},\n    #     {'name': 'Galaxy Gear', 'brand': 'Samsung', 'type': 'watch'}\n    # ]\n\n\n.. _where:\n\n``where()``\n-----------\n\nThe ``where`` method filters the collection by a given key / value pair:\n\n.. code-block:: python\n\n    collection = Collection([\n        {'name': 'Desk', 'price': 200},\n        {'name': 'Chair', 'price': 100},\n        {'name': 'Bookcase', 'price': 150},\n        {'name': 'Door', 'price': 100},\n    ])\n\n    filtered = collection.where('price', 100)\n\n    filtered.all()\n\n    # [\n    #     {'name': 'Chair', 'price': 100},\n    #     {'name': 'Door', 'price': 100}\n    # ]\n\n\n.. _zip:\n\n``zip()``\n---------\n\nThe ``zip`` method merges together the values of the given list\nwith the values of the collection at the corresponding index:\n\n.. code-block:: python\n\n    collection = Collection(['Chair', 'Desk'])\n\n    zipped = collection.zip([100, 200])\n\n    zipped.all()\n\n    # [('Chair', 100), ('Desk', 200)]",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Useful utilities for Python.",
    "version": "0.1",
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "md5": "d6e066f0b8897907068fb07fa42d3f4d",
                "sha256": "0162cf7b34c810ba4ddbbd32a1e5e804ef96fcf2fea5ce2848aa4950770d3893"
            },
            "downloads": -1,
            "filename": "backpack-0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "d6e066f0b8897907068fb07fa42d3f4d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 71308,
            "upload_time": "2016-08-04T21:11:21",
            "upload_time_iso_8601": "2016-08-04T21:11:21.237211Z",
            "url": "https://files.pythonhosted.org/packages/4e/d1/cd2034b49a3bea4cdc368a96d9d11043c71e6c13056f61976da720d89884/backpack-0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2016-08-04 21:11:21",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "github_user": "sdispater",
    "github_project": "backpack",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "simplejson",
            "specs": []
        }
    ],
    "tox": true,
    "lcname": "backpack"
}
        
Elapsed time: 0.01239s