Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/setuptools/_imp.py: 25%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

55 statements  

1""" 

2Re-implementation of find_module and get_frozen_object 

3from the deprecated imp module. 

4""" 

5 

6import importlib.machinery 

7import importlib.util 

8import os 

9import tokenize 

10from importlib.util import module_from_spec 

11 

12PY_SOURCE = 1 

13PY_COMPILED = 2 

14C_EXTENSION = 3 

15C_BUILTIN = 6 

16PY_FROZEN = 7 

17 

18 

19def find_spec(module, paths): 

20 finder = ( 

21 importlib.machinery.PathFinder().find_spec 

22 if isinstance(paths, list) 

23 else importlib.util.find_spec 

24 ) 

25 return finder(module, paths) 

26 

27 

28def find_module(module, paths=None): 

29 """Just like 'imp.find_module()', but with package support""" 

30 spec = find_spec(module, paths) 

31 if spec is None: 

32 raise ImportError("Can't find %s" % module) 

33 if not spec.has_location and hasattr(spec, 'submodule_search_locations'): 

34 spec = importlib.util.spec_from_loader('__init__.py', spec.loader) 

35 

36 kind = -1 

37 file = None 

38 static = isinstance(spec.loader, type) 

39 if ( 

40 spec.origin == 'frozen' 

41 or static 

42 and issubclass(spec.loader, importlib.machinery.FrozenImporter) 

43 ): 

44 kind = PY_FROZEN 

45 path = None # imp compabilty 

46 suffix = mode = '' # imp compatibility 

47 elif ( 

48 spec.origin == 'built-in' 

49 or static 

50 and issubclass(spec.loader, importlib.machinery.BuiltinImporter) 

51 ): 

52 kind = C_BUILTIN 

53 path = None # imp compabilty 

54 suffix = mode = '' # imp compatibility 

55 elif spec.has_location: 

56 path = spec.origin 

57 suffix = os.path.splitext(path)[1] 

58 mode = 'r' if suffix in importlib.machinery.SOURCE_SUFFIXES else 'rb' 

59 

60 if suffix in importlib.machinery.SOURCE_SUFFIXES: 

61 kind = PY_SOURCE 

62 file = tokenize.open(path) 

63 elif suffix in importlib.machinery.BYTECODE_SUFFIXES: 

64 kind = PY_COMPILED 

65 file = open(path, 'rb') 

66 elif suffix in importlib.machinery.EXTENSION_SUFFIXES: 

67 kind = C_EXTENSION 

68 

69 else: 

70 path = None 

71 suffix = mode = '' 

72 

73 return file, path, (suffix, mode, kind) 

74 

75 

76def get_frozen_object(module, paths=None): 

77 spec = find_spec(module, paths) 

78 if not spec: 

79 raise ImportError("Can't find %s" % module) 

80 return spec.loader.get_code(module) 

81 

82 

83def get_module(module, paths, info): 

84 spec = find_spec(module, paths) 

85 if not spec: 

86 raise ImportError("Can't find %s" % module) 

87 return module_from_spec(spec)