Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Handle cases when inspect.stack() fails

Mikhail Korobov8a1905e6ee85
diff --git a/scrapy/utils/deprecate.py b/scrapy/utils/deprecate.py
index edaecc3d3..767059476 100644
--- a/scrapy/utils/deprecate.py
+++ b/scrapy/utils/deprecate.py
@@ -95,10 +95,18 @@ def create_deprecated_class(name, new_class, clsdict=None,
return super(DeprecatedClass, cls).__call__(*args, **kwargs)
deprecated_cls = DeprecatedClass(name, (new_class,), clsdict or {})
- frm = inspect.stack()[1]
- parent_module = inspect.getmodule(frm[0])
- if parent_module is not None:
- deprecated_cls.__module__ = parent_module.__name__
+
+ try:
+ frm = inspect.stack()[1]
+ parent_module = inspect.getmodule(frm[0])
+ if parent_module is not None:
+ deprecated_cls.__module__ = parent_module.__name__
+ except Exception as e:
+ # Sometimes inspect.stack() fails (e.g. when the first import of
+ # deprecated class is in jinja2 template). __module__ attribute is not
+ # important enough to raise an exception as users may be unable
+ # to fix inspect.stack() errors.
+ warnings.warn("Error detecting parent module: %r" % e)
return deprecated_cls