GithubHelp home page GithubHelp logo

pomponchik / cantok Goto Github PK

View Code? Open in Web Editor NEW
94.0 3.0 4.0 1.21 MB

Implementation of the "Cancellation Token" pattern

Home Page: http://cantok.readthedocs.io/

License: MIT License

Python 100.00%
cancellationtoken threading threading-synchronization

cantok's Introduction

logo

Downloads Downloads codecov Lines of code Hits-of-Code Test-Package Python versions PyPI version Checked with mypy Ruff

Cancellation Token is a pattern that allows us to refuse to continue calculations that we no longer need. It is implemented out of the box in many programming languages, for example in C# and in Go. However, there was still no sane implementation in Python, until the cantok library appeared.

Quick start

Install it:

pip install cantok

And use:

from random import randint
from cantok import ConditionToken, CounterToken, TimeoutToken

token = ConditionToken(lambda: randint(1, 100_000) == 1984) + CounterToken(400_000, direct=False) + TimeoutToken(1)
counter = 0

while token:
  counter += 1

print(counter)

Read more in the documentation!

cantok's People

Contributors

pomponchik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

cantok's Issues

Оптимизация check

При вызове check приходится ходить по каждой ветке графа вложенных токенов.
Если хранить parent и вызывать cancel у parent при вызове cancel токена, то кажется при check в этом случае надо будет проверить только состояние текущего токена. В целом, в оригинальном подходе и в предложенном выше надо ходить по графу, но в предложенном варианте мы уже знаем по какой ветке надо идти, поэтому совокупное количество проходов значительно сократиться.

Вычитание токенов из общего токена

Чтобы токен можно было гонять много раз в виде целого объекта, если нужно несколько условий подряд соблюдать, не перебирать их, а если в ходе пайплайна нам уже не нужно один из токенов, можно было бы удалить ненужный + очистить память от ненужных токенов

Использовать condition variable в методе wait

Чтобы избежать такого кода и наличия параметра step

while token_for_wait:
     sync_sleep(step)

Можно использовать condition variable (привязанную к токену на котором вызываем wait):

with cv:
    while token_for_wait:
        cv.wait(timeout)

а в методе cancel:
вызывать cv.notify_all()

В оригинальном варианте такой подход осложнялся бы наличием вложенных токенов. Однако если использовать оптимизацию из предыдущего issue, то все должно работать.

P. S. единственное я не знаю как cv будет работать в случае async. По первым результатам из yandex поиска кажется, что можно заменить cv на asyncio.Event и все тоже получится.

Какое основное достоинство cantok по сравнению с Event из stdlib для реализации идеи "cancellation token"?

Допустим я хочу добавить cantok зависимость в набор инструментов, используемых командой. Какие основные аргументы можно озвучить в поддержку токенов из cantok по сравнению реализацией шаблона "cancellation token", используя {asyncio,threading,multiprocessing}.Event (is_set, wait, set методы)? (looking for elevator pitch)

Можно использовать cantok для отмены операции из другого сервиса, если общение между сервисами, через шину

Очень интересный доклад, первый раз услышала, про такой подход.

И возник вопрос, по use case:

Есть два сервиса, общающиеся через шину.
Второй сервис, выполнят pipline действия, достаточно продолжительно.
Как можно применить этот подход, для отмены операции, из первого сервиса?

И может, я не совсем поняла, где хранятся эти токены?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.