3

Is it possible to get the list of imported classes from a module?

My code is something like this:

from .models import Food, Drink, Topping

for m in (Food, Drink, Topping):
    admin.site.register(m)

where I always have to repeat the imported elements.

Is it possible to do something like:

from .models import Food, Drink, Topping

for m in list_of_things_imported_from[".models"]:
    admin.site.register(m)

I tried looking up on google and SO without good results.

ninazzo
  • 547
  • 1
  • 6
  • 17
  • I hope this link my help you. https://stackoverflow.com/questions/1796180/how-can-i-get-a-list-of-all-classes-within-current-module-in-python – Sarabjeet Sandhu Aug 08 '20 at 14:37
  • a comment before was suggesting dir(), but dir() first of all returns an array of strings, then I would have the overhead of getting the class from a string, and second it returns more things, not only the things imported from .models. – ninazzo Aug 08 '20 at 14:43

4 Answers4

3
import inspect
import test_module # module to be inspected

for name, data in inspect.getmembers(test_module):
    if name.startswith("__"):
        continue
    if 'class' in str(data):
        print(name)
0

One solution I just thought could be to make my own function that imports from .models and registers the elements, like

def import_and_register(arg_list):
    for a in arg_list:
        from .models import a
        admin.site.register(a)

But can I do this with a builtin feature? Are there any major cons to this approach?

ninazzo
  • 547
  • 1
  • 6
  • 17
  • One potential downside is the cognitive overhead for future programmers. It's a simple function, so I wouldn't call it a "major con" but if "everyone" does it the way you demonstrate in your original question, perhaps it's best to leave it alone. – bsoist Aug 08 '20 at 15:10
0

I don't believe there is, but perhaps to save yourself from typing remember the names, just store them in a collection.

from .models import Food, Drink, Topping

MY_FANCY_MODELS = Food, Drink, Topping

for m in MY_FANCY_MODELS:
    admin.site.register(m)

bsoist
  • 775
  • 3
  • 10
0

I feel, you can do it like this -

import models
for i in dir(models):
    if isinstance(i, type):
        admin.site.register(i)

dir(models) retrieves all the attributes of module.

Tabaene Haque
  • 576
  • 2
  • 10
  • But what if in models there's something I do not want to register? – ninazzo Aug 08 '20 at 14:54
  • Yes that's the downside of this approach. I suggested this approach based on the requirement `list_of_things_imported_from[".models"]` you asked in the question. – Tabaene Haque Aug 08 '20 at 15:00