You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently, the documentation says to replace celery.Task with a custom ContextTask. But this raises an error using mypy:
$ cat minimal.py
from flask import Flask
from celery import Celery, Task
def make_celery(app: Flask):
celery = Celery(app.import_name)
celery.conf.update(app.config["CELERY_CONFIG"])
class ContextTask(Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
celery.Task = ContextTask
return celery
$ mypy minimal.py
minimal.py:13: error: Property "Task" defined in "Celery" is read-only
minimal.py:13: error: Incompatible types in assignment (expression has type "Type[ContextTask]", variable has type "Task[Any]")
Instead one should initialize Celery with a string of the desired Task class. See Celery docs.
Invalid proposed solution
$ cat minimal.py
from flask import Flask
from celery import Celery, Task
class ContextTask(Task):
def __call__(self, *args, **kwargs):
with app.app_context():
return self.run(*args, **kwargs)
def make_celery(app: Flask):
celery = Celery(app.import_name, task_cls="minimal.minimal:ContextTask")
celery.conf.update(app.config["CELERY_CONFIG"])
return celery
$ mypy minimal.py
Success: no issues found in 1 source file
The text was updated successfully, but these errors were encountered:
sr-verde
changed the title
[DOC] Celery example:
[DOC] Celery Background Tasks: Property "Task" defined in "Celery" is read-only
Oct 5, 2022
davidism
changed the title
[DOC] Celery Background Tasks: Property "Task" defined in "Celery" is read-only
Celery Background Tasks: Property "Task" defined in "Celery" is read-only
Oct 5, 2022
The proposed fix isn't correct, it defeats the purpose of the Flask application factory function by referring to the app outside the function. That said, the current pattern isn't correct either if you're using the factory pattern for Flask as well.
However, I don't particularly care if MyPy doesn't think this is correct. MyPy isn't perfect, especially when it comes to completely valid Python patterns that large frameworks use but that MyPy hasn't figured out how support yet.
Currently, the documentation says to replace
celery.Task
with a customContextTask
. But this raises an error using mypy:Instead one should initialize Celery with a string of the desired Task class. See Celery docs.Invalid proposed solution
The text was updated successfully, but these errors were encountered: