lazy_load_template.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import importlib
  2. import random
  3. import re
  4. from ..utils import (
  5. age_restricted,
  6. bug_reports_message,
  7. classproperty,
  8. write_string,
  9. )
  10. # These bloat the lazy_extractors, so allow them to passthrough silently
  11. ALLOWED_CLASSMETHODS = {'get_testcases', 'extract_from_webpage'}
  12. _WARNED = False
  13. class LazyLoadMetaClass(type):
  14. def __getattr__(cls, name):
  15. global _WARNED
  16. if ('_real_class' not in cls.__dict__
  17. and name not in ALLOWED_CLASSMETHODS and not _WARNED):
  18. _WARNED = True
  19. write_string('WARNING: Falling back to normal extractor since lazy extractor '
  20. f'{cls.__name__} does not have attribute {name}{bug_reports_message()}\n')
  21. return getattr(cls.real_class, name)
  22. class LazyLoadExtractor(metaclass=LazyLoadMetaClass):
  23. @classproperty
  24. def real_class(cls):
  25. if '_real_class' not in cls.__dict__:
  26. cls._real_class = getattr(importlib.import_module(cls._module), cls.__name__)
  27. return cls._real_class
  28. def __new__(cls, *args, **kwargs):
  29. instance = cls.real_class.__new__(cls.real_class)
  30. instance.__init__(*args, **kwargs)
  31. return instance