Skip to content

Commit

Permalink
Use importlib on Python 3
Browse files Browse the repository at this point in the history
Use example from https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly
for importing files.
This eliminates deprecation warnings from importing 'imp' on Python 3.
  • Loading branch information
rodrigc committed Sep 1, 2017
1 parent 487f978 commit 9e53f41
Showing 1 changed file with 29 additions and 7 deletions.
36 changes: 29 additions & 7 deletions src/twisted/trial/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
]

import doctest
import imp
import inspect
import os
import sys
Expand All @@ -30,7 +29,7 @@
import warnings

from twisted.python import reflect, log, failure, modules, filepath
from twisted.python.compat import _PY3
from twisted.python.compat import _PY3, _PY35PLUS

from twisted.internet import defer
from twisted.trial import util, unittest
Expand All @@ -57,10 +56,21 @@ def isPackage(module):


def isPackageDirectory(dirname):
"""Is the directory at path 'dirname' a Python package directory?
"""
Is the directory at path 'dirname' a Python package directory?
Returns the name of the __init__ file (it may have a weird extension)
if dirname is a package directory. Otherwise, returns False"""
for ext in list(zip(*imp.get_suffixes()))[0]:
if dirname is a package directory. Otherwise, returns False
"""
def _getSuffixes():
if _PY3:
import importlib
return importlib.machinery.all_suffixes()
else:
import imp
return list(zip(*imp.get_suffixes()))[0]


for ext in _getSuffixes():
initFile = '__init__' + ext
if os.path.exists(os.path.join(dirname, initFile)):
return initFile
Expand Down Expand Up @@ -115,8 +125,20 @@ def _importFromFile(fn, moduleName=None):
moduleName = os.path.splitext(os.path.split(fn)[-1])[0]
if moduleName in sys.modules:
return sys.modules[moduleName]
with open(fn, 'r') as fd:
module = imp.load_source(moduleName, fn, fd)
if _PY35PLUS:
import importlib

spec = importlib.util.spec_from_file_location(moduleName, fn)
if not spec:
raise SyntaxError(fn)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
sys.modules[moduleName] = module
else:
import imp

with open(fn, 'r') as fd:
module = imp.load_source(moduleName, fn, fd)
return module


Expand Down

0 comments on commit 9e53f41

Please sign in to comment.