What is the meaning of bind = True keyword in celery?


What is the meaning of bind=True in below celery code? When to use it and when not?

def send_twitter_status(self, oauth, tweet):
        twitter = Twitter(oauth)
    except (Twitter.FailWhaleError, Twitter.LoginError) as exc:
        raise self.retry(exc=exc)
Asked By: Devang Padhiyar



The bind argument means that the function will be a “bound method” so that you can access attributes and methods on the task type instance.

See the docs

Answered By: Yugandhar Chaudhari

Bound tasks

A task being bound means the first argument to the task will always be the task instance (self), just like Python bound methods:

logger = get_task_logger(__name__)

def add(self, x, y):
Answered By: Devang Padhiyar

Just a small addition to other answers. As already stated, bound tasks have access to the task instance. One use case when this is needed are retries:

@celery.task(bind=True, max_retries=5)
def retrying(self):
        return 1/0
    except Exception:

Another use case is when you want to define custom states for your tasks and be able to set it during task execution:

def show_progress(self, n):
    for i in range(n):
        self.update_state(state='PROGRESS', meta={'current': i, 'total': n})
Answered By: Tomáš Linhart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.