Wraptor


NameWraptor JSON
Version 0.7.0 PyPI version JSON
download
home_pagehttp://github.com/carlsverre/wraptor
SummaryUseful decorators and other utility functions.
upload_time2018-05-05 02:21:28
maintainer
docs_urlNone
authorCarl Sverre
requires_python
licenseLICENSE.txt
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            ===========
Wraptor
===========

.. image:: https://github.com/carlsverre/wraptor/raw/master/docs/images/raptor.jpg

Testing
=======

.. image:: https://travis-ci.org/carlsverre/wraptor.png
    :target: https://travis-ci.org/carlsverre/wraptor

Run tests by executing :code:`make test`.

Decorators
==========

Memoize
-------
Add a cache to a function such that multiple calls with the same args
will return cached results.  Supports an optional cache timeout which
will flush items from the cache after a set interval for
recomputation.

.. code:: python

    from wraptor.decorators import memoize

    @memoize()
    def foo(bar, baz):
        print(bar, baz)

    foo(1, 2)
    # prints (1, 2)
    foo(3, 4)
    # prints (3, 4)
    foo(1, 2)
    # no-op

Supports timeouts!

.. code:: python

    @memoize(timeout=.5)
    def foo(bar, baz):
        print(bar, baz)

    foo(1, 2)
    # prints (1, 2)
    foo(1, 2)
    # no-op

    import time
    time.sleep(2)

    foo(1, 2)
    # prints (1, 2)

Supports attaching to an instance method!

.. code:: python

    class foo(object):
        @memoize(instance_method=True)
        def bar(self, a, b):
            return random()

    f = foo()
    f2 = foo()

    # they don't share a cache!
    f.bar(1,2) != f2.bar(1,2)

Throttle
--------
Throttle a function to firing at most 1 time per interval.  The function
is fired on the forward edge (meaning it will fire the first time you
call it).

.. code:: python

    from wraptor.decorators import throttle
    import time

    @throttle(.5)
    def foo(bar, baz):
        print(bar, baz)

    foo(1, 2)
    # prints (1, 2)
    foo(3, 4)
    # no-op
    time.sleep(1)
    foo(5, 6)
    # prints (1, 2)
    
Supports attaching to an instance method!

.. code:: python

    arr = []

    class foo(object):
        @throttle(1, instance_method=True)
        def bar(self):
            arr.append(1)

    x = foo()
    x2 = foo()

    x.bar()
    x2.bar()
    
    # they don't share the same throttle!
    assert arr == [1, 1]

By default throttle passes through the return value of the wrapped
function if it was called, or None if the def was not called. Use
`return_throttle_result=True` to instead return a `bool`:

.. code:: python

    @throttle(1, return_throttle_result=True)
    def foo():
        pass

    assert foo() is True, 'True means "called"'
    assert foo() is False, 'False means "not called" (throttled)'


Timeout
-------
Timeout uses signal under the hood to allow you to add timeouts to any
function.  The only caveat is that `signal.alarm` can only be used in the
main thread of execution (so multi-threading programs can't use this
decorator in sub-threads).

The timeout value must be a positive integer.

.. code:: python

    from wraptor.decorators import timeout, TimeoutException
    import time

    @timeout(1)
    def heavy_workload():
        # simulate heavy work
        time.sleep(10)

    try:
        heavy_workload()
    except TimeoutException:
        print('workload timed out')

You can also catch the timeout exception from inside the function:

.. code:: python

    @timeout(1)
    def heavy_workload():
        try:
            # simulate heavy work
            time.sleep(10)
        except TimeoutException:
            print('workload timed out')

Exception Catcher
-----------------
`exception_catcher` is a helpful method for dealing with threads that
may raise an exception.  It is especially useful for testing.

.. code:: python

    from wraptor.decorators import exception_catcher

    @exception_catcher
    def work():
        raise Exception()

    t = threading.Thread(target=work)
    t.start()
    t.join()

    try:
        work.check()
    except Exception as e:
        print e

Context Managers
================

Throttle
--------
Throttle a with statement to executing its body at most 1 time per
interval.  The body is fired on the forward edge (meaning it will
fire the first time you call it).

.. code:: python

    from wraptor.context import throttle
    import time

    throttler = throttle(seconds=3)

    def foo():
        with throttler:
            print 'bar'

    foo()
    # prints bar
    sleep(2)
    foo()
    # does nothing
    sleep(2)
    foo()
    # prints bar

Maybe
-----
Execute a with block based on the results of a predicate.

.. code:: python

    from wraptor.context import maybe

    def foo(cond):
        with maybe(lambda: cond == 5):
            print 'bar'

    foo(5)
    # prints bar
    foo(3)
    # does nothing

Timer
-----
Time a block of code.

.. code:: python

    from wraptor.context import timer

    def foo(cond):
        with timer('my slow method') as t:
            expensive_stuff()
        print t

    foo()
    # prints "my slow method took 435.694 ms"
            

Raw data

            {
    "_id": null,
    "home_page": "http://github.com/carlsverre/wraptor",
    "name": "Wraptor",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Carl Sverre",
    "author_email": "carl@carlsverre.com",
    "download_url": "https://files.pythonhosted.org/packages/50/8d/e3605669df8541f68a028dfd81db7f5b9b4d43bed133d070929f829eafce/Wraptor-0.7.0.tar.gz",
    "platform": "",
    "description": "===========\nWraptor\n===========\n\n.. image:: https://github.com/carlsverre/wraptor/raw/master/docs/images/raptor.jpg\n\nTesting\n=======\n\n.. image:: https://travis-ci.org/carlsverre/wraptor.png\n    :target: https://travis-ci.org/carlsverre/wraptor\n\nRun tests by executing :code:`make test`.\n\nDecorators\n==========\n\nMemoize\n-------\nAdd a cache to a function such that multiple calls with the same args\nwill return cached results.  Supports an optional cache timeout which\nwill flush items from the cache after a set interval for\nrecomputation.\n\n.. code:: python\n\n    from wraptor.decorators import memoize\n\n    @memoize()\n    def foo(bar, baz):\n        print(bar, baz)\n\n    foo(1, 2)\n    # prints (1, 2)\n    foo(3, 4)\n    # prints (3, 4)\n    foo(1, 2)\n    # no-op\n\nSupports timeouts!\n\n.. code:: python\n\n    @memoize(timeout=.5)\n    def foo(bar, baz):\n        print(bar, baz)\n\n    foo(1, 2)\n    # prints (1, 2)\n    foo(1, 2)\n    # no-op\n\n    import time\n    time.sleep(2)\n\n    foo(1, 2)\n    # prints (1, 2)\n\nSupports attaching to an instance method!\n\n.. code:: python\n\n    class foo(object):\n        @memoize(instance_method=True)\n        def bar(self, a, b):\n            return random()\n\n    f = foo()\n    f2 = foo()\n\n    # they don't share a cache!\n    f.bar(1,2) != f2.bar(1,2)\n\nThrottle\n--------\nThrottle a function to firing at most 1 time per interval.  The function\nis fired on the forward edge (meaning it will fire the first time you\ncall it).\n\n.. code:: python\n\n    from wraptor.decorators import throttle\n    import time\n\n    @throttle(.5)\n    def foo(bar, baz):\n        print(bar, baz)\n\n    foo(1, 2)\n    # prints (1, 2)\n    foo(3, 4)\n    # no-op\n    time.sleep(1)\n    foo(5, 6)\n    # prints (1, 2)\n    \nSupports attaching to an instance method!\n\n.. code:: python\n\n    arr = []\n\n    class foo(object):\n        @throttle(1, instance_method=True)\n        def bar(self):\n            arr.append(1)\n\n    x = foo()\n    x2 = foo()\n\n    x.bar()\n    x2.bar()\n    \n    # they don't share the same throttle!\n    assert arr == [1, 1]\n\nBy default throttle passes through the return value of the wrapped\nfunction if it was called, or None if the def was not called. Use\n`return_throttle_result=True` to instead return a `bool`:\n\n.. code:: python\n\n    @throttle(1, return_throttle_result=True)\n    def foo():\n        pass\n\n    assert foo() is True, 'True means \"called\"'\n    assert foo() is False, 'False means \"not called\" (throttled)'\n\n\nTimeout\n-------\nTimeout uses signal under the hood to allow you to add timeouts to any\nfunction.  The only caveat is that `signal.alarm` can only be used in the\nmain thread of execution (so multi-threading programs can't use this\ndecorator in sub-threads).\n\nThe timeout value must be a positive integer.\n\n.. code:: python\n\n    from wraptor.decorators import timeout, TimeoutException\n    import time\n\n    @timeout(1)\n    def heavy_workload():\n        # simulate heavy work\n        time.sleep(10)\n\n    try:\n        heavy_workload()\n    except TimeoutException:\n        print('workload timed out')\n\nYou can also catch the timeout exception from inside the function:\n\n.. code:: python\n\n    @timeout(1)\n    def heavy_workload():\n        try:\n            # simulate heavy work\n            time.sleep(10)\n        except TimeoutException:\n            print('workload timed out')\n\nException Catcher\n-----------------\n`exception_catcher` is a helpful method for dealing with threads that\nmay raise an exception.  It is especially useful for testing.\n\n.. code:: python\n\n    from wraptor.decorators import exception_catcher\n\n    @exception_catcher\n    def work():\n        raise Exception()\n\n    t = threading.Thread(target=work)\n    t.start()\n    t.join()\n\n    try:\n        work.check()\n    except Exception as e:\n        print e\n\nContext Managers\n================\n\nThrottle\n--------\nThrottle a with statement to executing its body at most 1 time per\ninterval.  The body is fired on the forward edge (meaning it will\nfire the first time you call it).\n\n.. code:: python\n\n    from wraptor.context import throttle\n    import time\n\n    throttler = throttle(seconds=3)\n\n    def foo():\n        with throttler:\n            print 'bar'\n\n    foo()\n    # prints bar\n    sleep(2)\n    foo()\n    # does nothing\n    sleep(2)\n    foo()\n    # prints bar\n\nMaybe\n-----\nExecute a with block based on the results of a predicate.\n\n.. code:: python\n\n    from wraptor.context import maybe\n\n    def foo(cond):\n        with maybe(lambda: cond == 5):\n            print 'bar'\n\n    foo(5)\n    # prints bar\n    foo(3)\n    # does nothing\n\nTimer\n-----\nTime a block of code.\n\n.. code:: python\n\n    from wraptor.context import timer\n\n    def foo(cond):\n        with timer('my slow method') as t:\n            expensive_stuff()\n        print t\n\n    foo()\n    # prints \"my slow method took 435.694 ms\"",
    "bugtrack_url": null,
    "license": "LICENSE.txt",
    "summary": "Useful decorators and other utility functions.",
    "version": "0.7.0",
    "project_urls": {
        "Homepage": "http://github.com/carlsverre/wraptor"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "508de3605669df8541f68a028dfd81db7f5b9b4d43bed133d070929f829eafce",
                "md5": "cf8a1f1215db239fbff46fa99391669b",
                "sha256": "d61182866a061fb29b7ec426db281cc9a15540766885136f35809f079d9c1dec"
            },
            "downloads": -1,
            "filename": "Wraptor-0.7.0.tar.gz",
            "has_sig": false,
            "md5_digest": "cf8a1f1215db239fbff46fa99391669b",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 5991,
            "upload_time": "2018-05-05T02:21:28",
            "upload_time_iso_8601": "2018-05-05T02:21:28.733969Z",
            "url": "https://files.pythonhosted.org/packages/50/8d/e3605669df8541f68a028dfd81db7f5b9b4d43bed133d070929f829eafce/Wraptor-0.7.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2018-05-05 02:21:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "carlsverre",
    "github_project": "wraptor",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "lcname": "wraptor"
}
        
Elapsed time: 0.28545s