Skip to content

Commit

Permalink
Fix deprecation warning with newer Pythons and 'imp' library.
Browse files Browse the repository at this point in the history
This warning is shown:
```
/opt/appuser/.local/lib/python3.9/site-packages/pyhocon/config_parser.py:4: DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses
    import imp

-- Docs: https://docs.pytest.org/en/stable/warnings.html
```

`imp.find_module()` (https://docs.python.org/3/library/imp.html#imp.find_module) was
deprecated since version 3.3.
However Pyhocon has no support for Python 3.3. We can use the alternative function
`importlib.util.find_spec()` (https://docs.python.org/3/library/importlib.html#importlib.util.find_spec)
which was added in Python 3.4 as advised in the docs.

See:#248
  • Loading branch information
olii committed Mar 4, 2021
1 parent e3f234b commit 5cff474
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions pyhocon/config_parser.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import codecs
import contextlib
import copy
import imp
import itertools
import logging
import os
Expand Down Expand Up @@ -63,6 +62,27 @@ def glob(pathname, recursive=False):
else:
from glob import glob


# Fix deprecated warning with 'imp' library and Python 3.4+.
# See: https://github.com/chimpler/pyhocon/issues/248
if sys.version_info >= (3, 4):
import importlib.util

def find_package_dir(name):
spec = importlib.util.find_spec(name)
# When `imp.find_module()` cannot find a package it raises ImportError.
# Here we should simulate it to keep the compatibility with older
# versions.
if not spec:
raise ImportError('No module named {!r}'.format(name))
return os.path.dirname(spec.origin)
else:
import imp

def find_package_dir(name):
return imp.find_module(name)[1]


logger = logging.getLogger(__name__)

#
Expand Down Expand Up @@ -727,7 +747,7 @@ def resolve_package_path(cls, package_path):
if ':' not in package_path:
raise ValueError("Expected format is 'PACKAGE:PATH'")
package_name, path_relative = package_path.split(':', 1)
package_dir = imp.find_module(package_name)[1]
package_dir = find_package_dir(package_name)
path_abs = os.path.join(package_dir, path_relative)
return path_abs

Expand Down

0 comments on commit 5cff474

Please sign in to comment.