Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1 

2class DummyException(Exception): 

3 pass 

4 

5 

6def import_global( 

7 name, modules=None, exceptions=DummyException, locals_=None, 

8 globals_=None, level=-1): 

9 '''Import the requested items into the global scope 

10 

11 WARNING! this method _will_ overwrite your global scope 

12 If you have a variable named "path" and you call import_global('sys') 

13 it will be overwritten with sys.path 

14 

15 Args: 

16 name (str): the name of the module to import, e.g. sys 

17 modules (str): the modules to import, use None for everything 

18 exception (Exception): the exception to catch, e.g. ImportError 

19 `locals_`: the `locals()` method (in case you need a different scope) 

20 `globals_`: the `globals()` method (in case you need a different scope) 

21 level (int): the level to import from, this can be used for 

22 relative imports 

23 ''' 

24 frame = None 

25 try: 

26 # If locals_ or globals_ are not given, autodetect them by inspecting 

27 # the current stack 

28 if locals_ is None or globals_ is None: 

29 import inspect 

30 frame = inspect.stack()[1][0] 

31 

32 if locals_ is None: 

33 locals_ = frame.f_locals 

34 

35 if globals_ is None: 

36 globals_ = frame.f_globals 

37 

38 try: 

39 name = name.split('.') 

40 

41 # Relative imports are supported (from .spam import eggs) 

42 if not name[0]: 

43 name = name[1:] 

44 level = 1 

45 

46 # raise IOError((name, level)) 

47 module = __import__( 

48 name=name[0] or '.', 

49 globals=globals_, 

50 locals=locals_, 

51 fromlist=name[1:], 

52 level=max(level, 0), 

53 ) 

54 

55 # Make sure we get the right part of a dotted import (i.e. 

56 # spam.eggs should return eggs, not spam) 

57 try: 

58 for attr in name[1:]: 

59 module = getattr(module, attr) 

60 except AttributeError: 

61 raise ImportError('No module named ' + '.'.join(name)) 

62 

63 # If no list of modules is given, autodetect from either __all__ 

64 # or a dir() of the module 

65 if not modules: 

66 modules = getattr(module, '__all__', dir(module)) 

67 else: 

68 modules = set(modules).intersection(dir(module)) 

69 

70 # Add all items in modules to the global scope 

71 for k in set(dir(module)).intersection(modules): 

72 if k and k[0] != '_': 

73 globals_[k] = getattr(module, k) 

74 except exceptions as e: 

75 return e 

76 finally: 

77 # Clean up, just to be sure 

78 del name, modules, exceptions, locals_, globals_, frame 

79