Tuesday, 25 October 2022

python __all__ variable, __all__ in django

 https://stackoverflow.com/questions/44834/what-does-all-mean-in-python


__all__ is used to export variables so other modules can use :



inked to, but not explicitly mentioned here, is exactly when __all__ is used. It is a list of strings defining what symbols in a module will be exported when from <module> import * is used on the module.

For example, the following code in a foo.py explicitly exports the symbols bar and baz:

__all__ = ['bar', 'baz']

waz = 5
bar = 10
def baz(): return 'baz'

These symbols can then be imported like so:

from foo import *

print(bar)
print(baz)

# The following will trigger an exception, as "waz" is not exported by the module
print(waz)

-----------------------------------------------------------------

__all__ is located in django __init__.py for each app, so what you have specified
 can be imported by other modules

for example :
django_celery/
├── __init__.py
├── asgi.py
├── celery.py
├── settings.py
├── urls.py
└── wsgi.py


# django_celery/celery.py
 2
 3import os
 4from celery import Celery
 5
 6os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_celery.settings")
 7app = Celery("django_celery")
 8app.config_from_object("django.conf:settings", namespace="CELERY")
 9app.autodiscover_tasks()

# this is to import app varaible from django_celery/celery.py and exported as celery_app so it can 
be picked up by celery

# django_celery/__init__.py

from .celery import app as celery_app

__all__ = ("celery_app",)

No comments:

Post a Comment