1 # encoding: utf-8 2 """ 3 Context managers for adding things to sys.path temporarily. 4 5 Authors: 6 7 * Brian Granger 8 """ 9 10 #----------------------------------------------------------------------------- 11 # Copyright (C) 2008-2011 The IPython Development Team 12 # 13 # Distributed under the terms of the BSD License. The full license is in 14 # the file COPYING, distributed as part of this software. 15 #----------------------------------------------------------------------------- 16 17 import sys 18 import warnings 19 20 21 class appended_to_syspath(object): 22 """ 23 Deprecated since IPython 8.1, no replacements. 24 25 A context for appending a directory to sys.path for a second.""" 26 27 def __init__(self, dir): 28 warnings.warn( 29 "`appended_to_syspath` is deprecated since IPython 8.1, and has no replacements", 30 DeprecationWarning, 31 stacklevel=2, 32 ) 33 self.dir = dir 34 35 def __enter__(self): 36 if self.dir not in sys.path: 37 sys.path.append(self.dir) 38 self.added = True 39 else: 40 self.added = False 41 42 def __exit__(self, type, value, traceback): 43 if self.added: 44 try: 45 sys.path.remove(self.dir) 46 except ValueError: 47 pass 48 # Returning False causes any exceptions to be re-raised. 49 return False 50 51 class prepended_to_syspath(object): 52 """A context for prepending a directory to sys.path for a second.""" 53 54 def __init__(self, dir): 55 self.dir = dir 56 57 def __enter__(self): 58 if self.dir not in sys.path: 59 sys.path.insert(0,self.dir) 60 self.added = True 61 else: 62 self.added = False 63 64 def __exit__(self, type, value, traceback): 65 if self.added: 66 try: 67 sys.path.remove(self.dir) 68 except ValueError: 69 pass 70 # Returning False causes any exceptions to be re-raised. 71 return False 72