It's interesting to figure out strange problems that come up due to API changes. Consider this awkward code:
import importlib try: from django.template.backends.django import get_installed_libraries from django.template.library import InvalidTemplateLibrary except ImportError: from django.template.base import get_library, InvalidTemplateLibrary def load_tag_library(libname): """Load a templatetag library on multiple Django versions. Returns None if the library isn't loaded. """ try: try: lib = get_installed_libraries()[libname] lib = importlib.import_module(lib).register return lib except NameError: lib = get_library(libname) return lib except (InvalidTemplateLibrary, KeyError): return None
I added this to django-extensions' compat.py file to handle
the removal of
django.template.base.get_library
in Django 1.9.
This function works but could be better. For example, it's
hard to see that the KeyError
is being caught
from get_installed_libraries()[libname]
. And what
if there was a legitimate KeyError
from the
except NameError
block? The exception would
get hidden and cause confusion for anyone trying to fix
the code.
import django def load_tag_library(libname): """Load a templatetag library on multiple Django versions. Returns None if the library isn't loaded. """ if django.VERSION < (1, 9): from django.template.base import get_library, InvalidTemplateLibrary try: lib = get_library(libname) return lib except InvalidTemplateLibrary: return None else: import importlib from django.template.backends.django import get_installed_libraries from django.template.library import InvalidTemplateLibrary try: lib = get_installed_libraries()[libname] lib = importlib.import_module(lib).register return lib except (InvalidTemplateLibrary, KeyError): return None
Is this code better? Who knows. At least it hides less legitimate exceptions.