@@ -130,6 +130,8 @@ def __call__(self, *args, **kwargs):
130130 """Call the Keyword's actual function with the given arguments.
131131 """
132132 func = self .func
133+ # the exception to finally reraise (if any)
134+ error = None
133135 # look for explicit <session>= and <context>= switching options
134136 # in kwargs and store the currently active
135137 # session aliases and context names
@@ -147,20 +149,29 @@ def __call__(self, *args, **kwargs):
147149 else :
148150 current_sessions [identifier , plural_identifier ] = getattr (
149151 self .libinstance , identifier )
150- getattr (self .libinstance , 'switch_' + identifier )(sname )
151- current_contexts = {}
152- for hcls in self .context_handlers :
153- if not getattr (hcls , 'auto_explicit' , False ):
154- continue
155- identifier = hcls .__name__ .lower ()
156- try :
157- ctxname = kwargs .pop (identifier )
158- except KeyError :
159- pass
160- else :
161- current_contexts [identifier ] = getattr (
162- self .libinstance , identifier )
163- getattr (self .libinstance , 'switch_' + identifier )(ctxname )
152+ switch = getattr (self .libinstance , 'switch_' + identifier )
153+ try :
154+ switch (sname )
155+ except hcls .SessionError as exc :
156+ error = exc
157+ # only perform explicit context switching
158+ # if explicit session switching didn't raise any error
159+ if error is not None :
160+ current_contexts = {}
161+ for hcls in self .context_handlers :
162+ if not getattr (hcls , 'auto_explicit' , False ):
163+ continue
164+ identifier = hcls .__name__ .lower ()
165+ try :
166+ ctxname = kwargs .pop (identifier )
167+ except KeyError :
168+ pass
169+ else :
170+ current_contexts [identifier ] = getattr (
171+ self .libinstance , identifier )
172+ switch = getattr (self .libinstance ,
173+ 'switch_' + identifier )
174+ switch (ctxname )
164175 # Look for arg type specs:
165176 if func .argtypes :
166177 casted = []
0 commit comments