', 'exec')
return []
- except Exception, error:
+ except Exception as error:
if isinstance(error, SyntaxError):
message = {'type': 'F',
'row': error.lineno,
@@ -672,7 +672,7 @@ def writeLocalPropertySheet(class_id, text, create=1, instance_home=None):
path = os.path.join(path, "%s.py" % class_id)
if create:
if os.path.exists(path):
- raise IOError, 'the file %s is already present' % path
+ raise IOError('the file %s is already present' % path)
with open(path, 'w') as f:
f.write(text)
# load the file, so that an error is raised if file is invalid
@@ -838,7 +838,7 @@ def writeLocalExtension(class_id, text, create=1, instance_home=None):
path = os.path.join(path, "%s.py" % class_id)
if create:
if os.path.exists(path):
- raise IOError, 'the file %s is already present' % path
+ raise IOError('the file %s is already present' % path)
with open(path, 'w') as f:
f.write(text)
@@ -852,7 +852,7 @@ def writeLocalTest(class_id, text, create=1, instance_home=None):
path = os.path.join(path, "%s.py" % class_id)
if create:
if os.path.exists(path):
- raise IOError, 'the file %s is already present' % path
+ raise IOError('the file %s is already present' % path)
with open(path, 'w') as f:
f.write(text)
@@ -866,7 +866,7 @@ def writeLocalConstraint(class_id, text, create=1, instance_home=None):
path = os.path.join(path, "%s.py" % class_id)
if create:
if os.path.exists(path):
- raise IOError, 'the file %s is already present' % path
+ raise IOError('the file %s is already present' % path)
with open(path, 'w') as f:
f.write(text)
# load the file, so that an error is raised if file is invalid
@@ -925,7 +925,7 @@ def writeLocalDocument(class_id, text, create=1, instance_home=None):
path = os.path.join(path, "%s.py" % class_id)
if create:
if os.path.exists(path):
- raise IOError, 'the file %s is already present' % path
+ raise IOError('the file %s is already present' % path)
# check there is no syntax error (that's the most we can do at this time)
compile(text, path, 'exec')
with open(path, 'w') as f:
@@ -1045,7 +1045,7 @@ def initializeLocalRegistry(directory_name, import_local_method):
LOG('ERP5Type', BLATHER,
'Added local %s to ERP5Type repository: %s (%s)'
% (directory_name, module_name, document_path))
- except Exception, e:
+ except Exception as e:
if DevelopmentMode:
raise
LOG('E5RP5Type', PROBLEM,
@@ -1319,7 +1319,7 @@ def evaluateExpressionFromString(expression_context, expression_string):
# An AttributeError is raised when instanciating an Expression
# class, and CompilerError and ValueError are raised in case of
# error when evaluation the expression
- except (AttributeError, CompilerError, ValueError), e:
+ except (AttributeError, CompilerError, ValueError) as e:
raise ValueError("Error in TALES expression: '%s': %s" % (expression_string,
str(e)))
@@ -1334,7 +1334,7 @@ def isValidTALESExpression(value):
"""
try:
ExpressionEngine.compile(value)
- except CompilerError, message:
+ except CompilerError as message:
return False, message
else:
return True, None
@@ -1364,7 +1364,7 @@ def assertAttributePortalType(o, attribute_name, portal_type):
portal_type = [portal_type]
if getattr(o, attribute_name).portal_type not in portal_type:
o._delObject(attribute_name)
- except (KeyError, AttributeError), err:
+ except (KeyError, AttributeError) as err:
LOG('ERP5Type', PROBLEM, "assertAttributePortalType failed on %s" % o,
error=err)
@@ -1732,7 +1732,7 @@ def guessEncodingFromText(data, content_type='text/html'):
else:
message = 'No suitable encoding detector found.'\
' You must install python-magic'
- raise NotImplementedError, message
+ raise NotImplementedError(message)
_reencodeUrlEscapes_map = {chr(x): chr(x) if chr(x) in
# safe
diff --git a/product/ERP5Type/WebDAVSupport.py b/product/ERP5Type/WebDAVSupport.py
index 69d782a33fd840a6b5610c7d50582bad0569dad1..67d54416821e5b87c716642d43d2be43c18cac90 100644
--- a/product/ERP5Type/WebDAVSupport.py
+++ b/product/ERP5Type/WebDAVSupport.py
@@ -119,7 +119,7 @@ class TextContent:
self.dav__init(REQUEST, RESPONSE)
self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
if REQUEST.environ['REQUEST_METHOD'] != 'PUT':
- raise Forbidden, 'REQUEST_METHOD should be PUT.'
+ raise Forbidden('REQUEST_METHOD should be PUT.')
body = REQUEST.get('BODY', '')
try:
@@ -128,14 +128,14 @@ class TextContent:
headers.setdefault('content_type', content_type)
headers['file'] = body
self._edit(**headers)
- except 'EditingConflict', msg:
+ except 'EditingConflict' as msg:
# XXX Can we get an error msg through? Should we be raising an
# exception, to be handled in the FTP mechanism? Inquiring
# minds...
transaction.abort()
RESPONSE.setStatus(450)
return RESPONSE
- except ResourceLockedError, msg:
+ except ResourceLockedError as msg:
transaction.abort()
RESPONSE.setStatus(423)
return RESPONSE
@@ -212,7 +212,7 @@ def PUT(self, REQUEST, RESPONSE):
self.dav__init(REQUEST, RESPONSE)
if REQUEST.environ['REQUEST_METHOD'] != 'PUT':
- raise Forbidden, 'REQUEST_METHOD should be PUT.'
+ raise Forbidden('REQUEST_METHOD should be PUT.')
name = self.__name__
parent = self.__parent__
diff --git a/product/ERP5Type/dynamic/component_package.py b/product/ERP5Type/dynamic/component_package.py
index bbc3bfbeec9e4c7e263abcc70d05f34385a56109..64ab5770dd208bcb26f947a3d625d8031a49b2dd 100644
--- a/product/ERP5Type/dynamic/component_package.py
+++ b/product/ERP5Type/dynamic/component_package.py
@@ -234,7 +234,7 @@ class ComponentDynamicPackage(ModuleType):
try:
version, name = name.split('.')
version = version[:-self.__version_suffix_len]
- except ValueError, error:
+ except ValueError as error:
raise ImportError("%s: should be %s.VERSION.COMPONENT_REFERENCE (%s)" % \
(fullname, self._namespace, error))
@@ -300,7 +300,7 @@ class ComponentDynamicPackage(ModuleType):
# in a deadlock
source_code_obj = compile(source_code_str, module.__file__, 'exec')
exec source_code_obj in module.__dict__
- except Exception, error:
+ except Exception as error:
del sys.modules[module_fullname]
if module_fullname_alias:
del sys.modules[module_fullname_alias]
diff --git a/product/ERP5Type/dynamic/lazy_class.py b/product/ERP5Type/dynamic/lazy_class.py
index cddb6749b3e734d4ce0abc8c0f05b6064e09326c..d6b55880ad901c23709506b3695e0e9267e2c8d0 100644
--- a/product/ERP5Type/dynamic/lazy_class.py
+++ b/product/ERP5Type/dynamic/lazy_class.py
@@ -115,7 +115,7 @@ class GhostBaseMetaClass(ExtensionClass, AccessorHolderType):
self.__class__.loadClass()
except ConflictError:
raise
- except Exception, e:
+ except Exception as e:
LOG('lazy_class.__getattribute__', WARNING, 'Failed to load class : %r' % (e,),
error=sys.exc_info())
raise
diff --git a/product/ERP5Type/mixin/component.py b/product/ERP5Type/mixin/component.py
index 7f6183f4fad5426295da9a4f748d0bffe10aa4f4..21e1768dd70be2e6f3105241a344957e24700e72 100644
--- a/product/ERP5Type/mixin/component.py
+++ b/product/ERP5Type/mixin/component.py
@@ -317,7 +317,7 @@ class ComponentMixin(PropertyRecordableMixin, Base):
self.dav__init(REQUEST, RESPONSE)
self.dav__simpleifhandler(REQUEST, RESPONSE, refresh=1)
if REQUEST.environ['REQUEST_METHOD'] != 'PUT':
- raise Forbidden, 'REQUEST_METHOD should be PUT.'
+ raise Forbidden('REQUEST_METHOD should be PUT.')
text_content = REQUEST.get('BODY')
if text_content is None:
diff --git a/product/ERP5Type/mixin/matrix.py b/product/ERP5Type/mixin/matrix.py
index 8101b17b760bbddfc7c331b5e04ce371851ee6b2..c9e7478e6cb0983220136fbba9de63d58001a8e4 100644
--- a/product/ERP5Type/mixin/matrix.py
+++ b/product/ERP5Type/mixin/matrix.py
@@ -200,9 +200,8 @@ class Matrix(object):
"""
script = self._getTypeBasedMethod('asCellRange', **kw)
if script is None:
- raise UnboundLocalError,\
- "Did not find cell range script for portal type: %r" %\
- self.getPortalType()
+ raise UnboundLocalError("Did not find cell range script for portal type: %r" %\
+ self.getPortalType())
cell_range = script(base_id=base_id, matrixbox=0, **kw)
self._setCellRange(base_id=base_id, *cell_range)
@@ -336,7 +335,7 @@ class Matrix(object):
cell_id = self.keyToId(kw, base_id = base_id)
if cell_id is None:
- raise KeyError, 'Invalid key: %s' % str(kw)
+ raise KeyError('Invalid key: %s' % str(kw))
cell = self.get(cell_id)
if cell is not None:
diff --git a/product/ERP5Type/patches/CMFBTreeFolder.py b/product/ERP5Type/patches/CMFBTreeFolder.py
index 6162af7af66627bc42f8fdbd9c0767fa0a310708..481b33e000a93bb667c716c913a712d5530cbf8a 100644
--- a/product/ERP5Type/patches/CMFBTreeFolder.py
+++ b/product/ERP5Type/patches/CMFBTreeFolder.py
@@ -40,9 +40,9 @@ def CMFBTreeFolder_allowedContentTypes(self):
for portal_type in myType.getTypeAllowedContentTypeList():
contentType = portal_types.getTypeInfo(portal_type)
if contentType is None:
- raise AttributeError, "Portal type '%s' does not exist " \
+ raise AttributeError("Portal type '%s' does not exist " \
"and should not be allowed in '%s'" % \
- (portal_type, self.getPortalType())
+ (portal_type, self.getPortalType()))
result.append(contentType)
else:
for contentType in portal_types.listTypeInfo(self):
diff --git a/product/ERP5Type/patches/CMFCoreSkinnable.py b/product/ERP5Type/patches/CMFCoreSkinnable.py
index cdbba4af1ada0d9302ba031fe755b82b11175902..231b22df18d3bb5bd77d43623f551e0e4ad5d0cc 100644
--- a/product/ERP5Type/patches/CMFCoreSkinnable.py
+++ b/product/ERP5Type/patches/CMFCoreSkinnable.py
@@ -69,7 +69,7 @@ def skinResolve(self, selection, name):
try:
portal_skins = aq_base(self.portal_skins)
except AttributeError:
- raise AttributeError, name
+ raise AttributeError(name)
try:
portal_callables = aq_base(self.portal_callables)
except AttributeError:
@@ -163,7 +163,7 @@ def CMFCoreSkinnableSkinnableObjectManager_getSkin(self, name=None):
calls.
FIXME: Which exception should be raised here ?
"""
- raise Exception, 'This method must not be called when new caching system is applied.'
+ raise Exception('This method must not be called when new caching system is applied.')
Skinnable.SkinnableObjectManager.__getattr__ = CMFCoreSkinnableSkinnableObjectManager___getattr__
Skinnable.SkinnableObjectManager.changeSkin = CMFCoreSkinnableSkinnableObjectManager_changeSkin
diff --git a/product/ERP5Type/patches/CachingPolicyManager.py b/product/ERP5Type/patches/CachingPolicyManager.py
index 30e847f27a23d52bfe8a4afc681d672edc806b71..a1885a872e3577c2657b3e1ee42df574bd4abad4 100644
--- a/product/ERP5Type/patches/CachingPolicyManager.py
+++ b/product/ERP5Type/patches/CachingPolicyManager.py
@@ -310,7 +310,7 @@ def _updatePolicy( self
Update a policy in our registry.
"""
if policy_id not in self._policy_ids:
- raise KeyError, "Policy %s does not exist!" % policy_id
+ raise KeyError("Policy %s does not exist!" % policy_id)
self._policies[ policy_id ] = CachingPolicy( policy_id
, predicate
@@ -446,10 +446,10 @@ def _addPolicy( self
policy_id = str( policy_id ).strip()
if not policy_id:
- raise ValueError, "Policy ID is required!"
+ raise ValueError("Policy ID is required!")
if policy_id in self._policy_ids:
- raise KeyError, "Policy %s already exists!" % policy_id
+ raise KeyError("Policy %s already exists!" % policy_id)
self._policies[ policy_id ] = CachingPolicy( policy_id
, predicate
diff --git a/product/ERP5Type/patches/DA.py b/product/ERP5Type/patches/DA.py
index 3b42902785045d12da0ca02f47ae78bc07f1ce3a..c9fcb0efe22a16549bdf65f8442fa885d5252929 100644
--- a/product/ERP5Type/patches/DA.py
+++ b/product/ERP5Type/patches/DA.py
@@ -187,12 +187,12 @@ def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
#LOG("DA__call__ connection", 300, c)
try: dbc=getattr(self, c)
except AttributeError:
- raise AttributeError, (
+ raise AttributeError(
"The database connection %s cannot be found." % (
c))
try: DB__=dbc()
- except: raise DatabaseError, (
+ except: raise DatabaseError(
'%s is not connected to a database' % self.id)
p = aq_parent(self) # None if no aq_parent
@@ -205,7 +205,7 @@ def DA__call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw):
security.addContext(self)
try:
query = self.template(p, **argdata)
- except TypeError, msg:
+ except TypeError as msg:
msg = str(msg)
if 'client' in msg:
raise NameError("'client' may not be used as an "
diff --git a/product/ERP5Type/patches/DCWorkflow.py b/product/ERP5Type/patches/DCWorkflow.py
index 94de021bccc46fc9a69be8c0988f9c813bb51504..09ec191615fc9c0b157c539e9182fc2b484ae466 100644
--- a/product/ERP5Type/patches/DCWorkflow.py
+++ b/product/ERP5Type/patches/DCWorkflow.py
@@ -415,11 +415,11 @@ def DCWorkflowDefinition_executeTransition(self, ob, tdef=None, kwargs=None):
try:
#LOG('_executeTransition', 0, "script = %s, sci = %s" % (repr(script), repr(sci)))
script(sci) # May throw an exception.
- except ValidationFailed, validation_exc:
+ except ValidationFailed as validation_exc:
before_script_success = 0
before_script_error_message = deepcopy(validation_exc.msg)
validation_exc_traceback = sys.exc_traceback
- except ObjectMoved, moved_exc:
+ except ObjectMoved as moved_exc:
ob = moved_exc.getNewObject()
# Re-raise after transition
@@ -533,7 +533,7 @@ def _executeMetaTransition(self, ob, new_state_id):
new_sdef = self.states.get(new_state_id, None)
if new_sdef is None:
- raise WorkflowException, ('Destination state undefined: ' + new_state_id)
+ raise WorkflowException('Destination state undefined: ' + new_state_id)
# Update variables.
state_values = new_sdef.var_values
@@ -587,12 +587,12 @@ def DCWorkflowDefinition_wrapWorkflowMethod(self, ob, method_id, func, args, kw)
'''
sdef = self._getWorkflowStateOf(ob)
if sdef is None:
- raise WorkflowException, 'Object is in an undefined state'
+ raise WorkflowException('Object is in an undefined state')
if method_id not in sdef.transitions:
raise Unauthorized(method_id)
tdef = self.transitions.get(method_id, None)
if tdef is None or tdef.trigger_type != TRIGGER_WORKFLOW_METHOD:
- raise WorkflowException, (
+ raise WorkflowException(
'Transition %s is not triggered by a workflow method'
% method_id)
if not self._checkTransitionGuard(tdef, ob):
@@ -603,7 +603,7 @@ def DCWorkflowDefinition_wrapWorkflowMethod(self, ob, method_id, func, args, kw)
except ObjectDeleted:
# Re-raise with a different result.
raise ObjectDeleted(res)
- except ObjectMoved, ex:
+ except ObjectMoved as ex:
# Re-raise with a different result.
raise ObjectMoved(ex.getNewObject(), res)
return res
diff --git a/product/ERP5Type/patches/DateTimePatch.py b/product/ERP5Type/patches/DateTimePatch.py
index 5dea0db3d5490f9384837db24718a29f3ec8d1a7..e9eb1e5b4463dc3ed529d328501bb7460d7b7bed 100644
--- a/product/ERP5Type/patches/DateTimePatch.py
+++ b/product/ERP5Type/patches/DateTimePatch.py
@@ -130,18 +130,18 @@ def DateTime_parse(self, st, datefmt=getDefaultDateFormat()):
if MonthNumbers.has_key(s):
v=MonthNumbers[s]
if month is None: month=v
- else: raise SyntaxError, st
+ else: raise SyntaxError(st)
continue
# Check for time modifier:
if s in TimeModifiers:
if tm is None: tm=s
- else: raise SyntaxError, st
+ else: raise SyntaxError(st)
continue
# Check for and skip day of week:
if DayOfWeekNames.has_key(s):
continue
- raise SyntaxError, st
+ raise SyntaxError(st)
day=None
if ints[-1] > 60 and d not in ['.',':','/'] and len(ints) > 2:
@@ -210,29 +210,29 @@ def DateTime_parse(self, st, datefmt=getDefaultDateFormat()):
leap = year%4==0 and (year%100!=0 or year%400==0)
try:
if not day or day > self._month_len[leap][month]:
- raise DateError, st
+ raise DateError(st)
except IndexError:
- raise DateError, st
+ raise DateError(st)
tod=0
if ints:
i=ints[0]
# Modify hour to reflect am/pm
if tm and (tm=='pm') and i<12: i=i+12
if tm and (tm=='am') and i==12: i=0
- if i > 24: raise TimeError, st
+ if i > 24: raise TimeError(st)
tod = tod + int(i) * 3600
del ints[0]
if ints:
i=ints[0]
- if i > 60: raise TimeError, st
+ if i > 60: raise TimeError(st)
tod = tod + int(i) * 60
del ints[0]
if ints:
i=ints[0]
- if i > 60: raise TimeError, st
+ if i > 60: raise TimeError(st)
tod = tod + i
del ints[0]
- if ints: raise SyntaxError,st
+ if ints: raise SyntaxError(st)
tod_int = int(math.floor(tod))
diff --git a/product/ERP5Type/patches/DemoStorage.py b/product/ERP5Type/patches/DemoStorage.py
index 87ce80303f07974ff1dcdb699aa2c3c227b11f38..6d76f73adf43bc7dd01be7785521e3fb8f73b788 100644
--- a/product/ERP5Type/patches/DemoStorage.py
+++ b/product/ERP5Type/patches/DemoStorage.py
@@ -25,7 +25,7 @@ class DemoStorage(_DemoStorage.DemoStorage, ConflictResolvingStorage):
try:
return super(DemoStorage, self).store(
oid, serial, data, version, transaction)
- except ConflictError, e:
+ except ConflictError as e:
old = e.serials[0]
rdata = self.tryToResolveConflict(oid, old, serial, data)
self.changes.store(oid, old, rdata, '', transaction)
diff --git a/product/ERP5Type/patches/ExceptionFormatter.py b/product/ERP5Type/patches/ExceptionFormatter.py
index 9931e103f80a5fe8bccd14682f493ee73a2dc05d..bc97df5fe6eb71fb104d53cea80c95c7371cfe28 100644
--- a/product/ERP5Type/patches/ExceptionFormatter.py
+++ b/product/ERP5Type/patches/ExceptionFormatter.py
@@ -90,7 +90,7 @@ def formatLine(self, tb, *args, **kwargs):
line_str,
flags=re.DOTALL)
- except Exception, e:
+ except Exception as e:
pass
return line_str
diff --git a/product/ERP5Type/patches/OFSImage.py b/product/ERP5Type/patches/OFSImage.py
index aacfde27ceac2c087664ee2d94c9ba301ce92db5..416ba85bcc93ff9303f840dd914264f0bbbd022b 100644
--- a/product/ERP5Type/patches/OFSImage.py
+++ b/product/ERP5Type/patches/OFSImage.py
@@ -90,7 +90,7 @@ PUT_orig = OFS.Image.File.PUT
def PUT(self, REQUEST, RESPONSE):
"""Handle HTTP PUT requests"""
if REQUEST.environ['REQUEST_METHOD'] != 'PUT':
- raise Forbidden, 'REQUEST_METHOD should be PUT.'
+ raise Forbidden('REQUEST_METHOD should be PUT.')
return PUT_orig(self, REQUEST, RESPONSE)
OFS.Image.File.PUT = PUT
diff --git a/product/ERP5Type/patches/PropertyManager.py b/product/ERP5Type/patches/PropertyManager.py
index 7ebc277480ca64db2d31b05d5030894d46d34198..3ea296d9428b07ce2aa68865df2e96ec39506bc2 100644
--- a/product/ERP5Type/patches/PropertyManager.py
+++ b/product/ERP5Type/patches/PropertyManager.py
@@ -41,7 +41,7 @@ def PropertyManager_updateProperty(self, id, value, local_properties=False):
self._wrapperCheck(value)
if not hasattr(self, 'isRADContent'):
if not self.hasProperty(id):
- raise BadRequest, 'The property %s does not exist' % escape(id)
+ raise BadRequest('The property %s does not exist' % escape(id))
if isinstance(value, str):
proptype=self.getPropertyType(id, local_properties=local_properties) \
or 'string'
@@ -110,11 +110,11 @@ def PropertyManager_setProperty(self, id, value, type=None):
self._wrapperCheck(value)
if not self.valid_property_id(id):
- raise BadRequest, 'Invalid or duplicate property id: %s' % id
+ raise BadRequest('Invalid or duplicate property id: %s' % id)
if type in ('selection', 'multiple selection'):
if not hasattr(self, value):
- raise BadRequest, 'No select variable %s' % value
+ raise BadRequest('No select variable %s' % value)
self._local_properties=getattr(self, '_local_properties', ()) + (
{'id':id, 'type':type, 'select_variable':value},)
if type=='selection':
@@ -140,7 +140,7 @@ def PropertyManager_valid_property_id(self, id):
def PropertyManager_delProperty(self, id):
if not self.hasProperty(id):
- raise ValueError, 'The property %s does not exist' % escape(id)
+ raise ValueError('The property %s does not exist' % escape(id))
self._delPropValue(id)
self._local_properties=tuple(filter(lambda i, n=id: i['id'] != n,
getattr(self, '_local_properties', ())))
diff --git a/product/ERP5Type/patches/WebDAV.py b/product/ERP5Type/patches/WebDAV.py
index 67929105b8d56f9f76fd12c21332f7622999e30d..5d757860ab50e3ea73f79453996f8292cc06d0ec 100644
--- a/product/ERP5Type/patches/WebDAV.py
+++ b/product/ERP5Type/patches/WebDAV.py
@@ -27,15 +27,15 @@ def MKCOL(self, REQUEST, RESPONSE):
"""Create a new collection resource."""
self.dav__init(REQUEST, RESPONSE)
if REQUEST.get('BODY', ''):
- raise UnsupportedMediaType, 'Unknown request body.'
+ raise UnsupportedMediaType('Unknown request body.')
name=self.__name__
parent = self.__parent__
if hasattr(aq_base(parent), name):
- raise MethodNotAllowed, 'The name %s is in use.' % name
+ raise MethodNotAllowed('The name %s is in use.' % name)
if not isDavCollection(parent):
- raise Forbidden, 'Cannot create collection at this location.'
+ raise Forbidden('Cannot create collection at this location.')
ifhdr = REQUEST.get_header('If', '')
if IWriteLock.providedBy(parent) and parent.wl_isLocked():
diff --git a/product/ERP5Type/patches/WorkflowTool.py b/product/ERP5Type/patches/WorkflowTool.py
index 9497854e894e9e357ee686fa43430f0bf59a8920..9dd1eef1b1a4937e9aab4e1e4d27a886c1d8f43a 100644
--- a/product/ERP5Type/patches/WorkflowTool.py
+++ b/product/ERP5Type/patches/WorkflowTool.py
@@ -57,12 +57,12 @@ def DCWorkflowDefinition_notifyWorkflowMethod(self, ob, transition_list, args=No
raise ValueError('WorkflowMethod should be attached to exactly 1 transition per DCWorkflow instance.')
sdef = self._getWorkflowStateOf(ob)
if sdef is None:
- raise WorkflowException, 'Object is in an undefined state'
+ raise WorkflowException('Object is in an undefined state')
if method_id not in sdef.transitions:
raise Unauthorized(method_id)
tdef = self.transitions.get(method_id, None)
if tdef is None or tdef.trigger_type != TRIGGER_WORKFLOW_METHOD:
- raise WorkflowException, (
+ raise WorkflowException(
'Transition %s is not triggered by a workflow method'
% method_id)
if not self._checkTransitionGuard(tdef, ob):
@@ -567,13 +567,13 @@ def WorkflowTool_listActions(self, info=None, object=None, src__=False):
% grouped_worklist_dict.keys(),
error=sys.exc_info())
continue
- except ProgrammingError, error_value:
+ except ProgrammingError as error_value:
# 1146 = table does not exist
if not use_cache or error_value[0] != 1146:
raise
try:
self.Base_zCreateWorklistTable()
- except ProgrammingError, error_value:
+ except ProgrammingError as error_value:
# 1050 = table exists (alarm run just a bit too late)
if error_value[0] != 1050:
raise
@@ -649,7 +649,7 @@ def WorkflowTool_refreshWorklistCache(self):
else:
try:
self.Base_zClearWorklistTable()
- except ProgrammingError, error_value:
+ except ProgrammingError as error_value:
# 1146 = table does not exist
if error_value[0] != 1146:
raise
@@ -709,7 +709,7 @@ def WorkflowTool_refreshWorklistCache(self):
if len(value_column_dict[COUNT_COLUMN_TITLE]):
try:
Base_zInsertIntoWorklistTable(**value_column_dict)
- except (ProgrammingError, OperationalError), error_value:
+ except (ProgrammingError, OperationalError) as error_value:
# OperationalError 1054 = unknown column
if isinstance(error_value, OperationalError) and error_value[0] != 1054:
raise
@@ -756,7 +756,7 @@ class WorkflowHistoryList(Persistent):
return self.__class__((self[x] for x in
xrange(*index.indices(len(self)))))
else:
- raise TypeError, 'tuple indices must be integers'
+ raise TypeError('tuple indices must be integers')
def __getslice__(self, start, end):
return self.__getitem__(slice(start, end))
@@ -898,7 +898,7 @@ class WorkflowMethod( Method ):
# No workflow tool found.
try:
res = self._m(instance, *args, **kw)
- except ObjectDeleted, ex:
+ except ObjectDeleted as ex:
res = ex.getResult()
else:
if hasattr(aq_base(instance), 'reindexObject'):
diff --git a/product/ERP5Type/patches/memcache_client.py b/product/ERP5Type/patches/memcache_client.py
index d4cf6327abfdde8948cc06b4451cbd8f24f58ac6..9a808a259e71800723ba0960fbc332adfbb5a522 100644
--- a/product/ERP5Type/patches/memcache_client.py
+++ b/product/ERP5Type/patches/memcache_client.py
@@ -60,7 +60,7 @@ else:
except TypeError:
# BBB
server.expect("END")
- except (_Error, socket.error), msg:
+ except (_Error, socket.error) as msg:
if isinstance(msg, tuple): msg = msg[1]
server.mark_dead(msg)
# (patch)
@@ -79,7 +79,7 @@ else:
# (patch)
# return None
raise _ConnectionDeadError
- except (_ConnectionDeadError, socket.error), msg:
+ except (_ConnectionDeadError, socket.error) as msg:
server.mark_dead(msg)
# (patch)
# return None
diff --git a/product/ERP5Type/patches/pylint.py b/product/ERP5Type/patches/pylint.py
index 459d8801a881c35f7053ebb0f945c4a47024a5d7..9f67560ec0fa126ae54fe347089232429444d9af 100644
--- a/product/ERP5Type/patches/pylint.py
+++ b/product/ERP5Type/patches/pylint.py
@@ -39,7 +39,7 @@ else:
def _get_imported_module(self, importnode, modname):
try:
return importnode.do_import_module(modname)
- except astroid.InferenceError, ex:
+ except astroid.InferenceError as ex:
# BEGIN
# XXX-arnau: Ignore ERP5 dynamic modules, hackish but required
diff --git a/product/ERP5Type/patches/sqltest.py b/product/ERP5Type/patches/sqltest.py
index 43e468fd5fe1686c6b838477301c958814c538b3..03dcc9e0752ca548e55bcdb62f23625b3fbef584 100644
--- a/product/ERP5Type/patches/sqltest.py
+++ b/product/ERP5Type/patches/sqltest.py
@@ -31,13 +31,13 @@ if 1: # For easy diff with original
except (KeyError, NameError):
if args.has_key('optional') and args['optional']:
return ''
- raise ValueError, 'Missing input variable, %s' % name
+ raise ValueError('Missing input variable, %s' % name)
# PATCH: use isinstance instead of type comparison, to allow
# subclassing.
if isinstance(v, list_type_list):
if len(v) > 1 and not self.multiple:
- raise ValueError, (
+ raise ValueError(
'multiple values are not allowed for %s'
% name)
else: v=[v]
@@ -53,7 +53,7 @@ if 1: # For easy diff with original
atoi(v)
else: v=str(int(v))
except ValueError:
- raise ValueError, (
+ raise ValueError(
'Invalid integer value for %s' % name)
elif t=='float':
if not v and type(v) is StringType: continue
@@ -61,7 +61,7 @@ if 1: # For easy diff with original
if type(v) is StringType: atof(v)
else: v=str(float(v))
except ValueError:
- raise ValueError, (
+ raise ValueError(
'Invalid floating-point value for %s' % name)
elif t.startswith('datetime'):
# For subsecond precision, use 'datetime(N)' MySQL type,
@@ -84,12 +84,12 @@ if 1: # For easy diff with original
return ''
else:
err = 'Invalid empty string value for %s' % name
- raise ValueError, err
+ raise ValueError(err)
if not vs:
if self.optional: return ''
- raise ValueError, (
+ raise ValueError(
'No input was provided for %s' % name)
if len(vs) > 1:
diff --git a/product/ERP5Type/patches/unicodeconflictresolver.py b/product/ERP5Type/patches/unicodeconflictresolver.py
index 1d12c5ef76d7008b49991eb5091aceaffc7e435f..1c2c7dd4154baa222ddab2e7651fb500a04915d8 100644
--- a/product/ERP5Type/patches/unicodeconflictresolver.py
+++ b/product/ERP5Type/patches/unicodeconflictresolver.py
@@ -32,7 +32,7 @@ def PreferredCharsetResolver_resolve(context, text, expression):
# requests that do not contain Accept-Charset header.
try:
result = unicode(text, 'utf-8')
- except UnicodeDecodeError, e:
+ except UnicodeDecodeError as e:
tb_info = ''.join(traceback.format_stack())
logger.warn('UnicodeDecodeError(%s: %s): %s\ntext: %r\nat:\n%s' %
(e.start, e.end, e.reason, repr(text), tb_info))
diff --git a/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py b/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py
index a6af4e8095944510da51ebe46870167364054fb1..f2a7fdbd3625f21f47f9a3af503975918750b204 100644
--- a/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py
+++ b/product/ERP5Type/tests/ERP5TypeFunctionalTestCase.py
@@ -351,7 +351,7 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase):
error = None
try:
iframe = self.runner.test(debug=debug)
- except TimeoutError, e:
+ except TimeoutError as e:
error = repr(e)
self._verboseErrorLog(20)
else:
@@ -385,6 +385,6 @@ class ERP5TypeFunctionalTestCase(ERP5TypeTestCase):
# authentication dialog in case of Unauthorized exception to prevent
# blocking in functional tests.
def _unauthorized(self):
- raise RuntimeError, 'Unauthorized exception happens.'
+ raise RuntimeError('Unauthorized exception happens.')
HTTPResponse._unauthorized = _unauthorized
diff --git a/product/ERP5Type/tests/ERP5TypeTestCase.py b/product/ERP5Type/tests/ERP5TypeTestCase.py
index 52807b52567df34e668068112c134c8574057456..1258f41122e9cc145fd12c641a844ed6f970a7f7 100644
--- a/product/ERP5Type/tests/ERP5TypeTestCase.py
+++ b/product/ERP5Type/tests/ERP5TypeTestCase.py
@@ -750,7 +750,7 @@ class ERP5TypeTestCaseMixin(ProcessingNodeTestCase, PortalTestCase):
elif len(p) == 2:
[env['PATH_INFO'], env['QUERY_STRING']] = p
else:
- raise TypeError, ''
+ raise TypeError('')
if basic:
assert not user, (basic, user)
@@ -1412,7 +1412,7 @@ class ZEOServerTestCase(ERP5TypeTestCase):
try:
self.zeo_server = StorageServer(host_port, storage)
break
- except socket.error, e:
+ except socket.error as e:
if e[0] != errno.EADDRINUSE:
raise
if zeo_client:
diff --git a/product/ERP5Type/tests/ERP5TypeTestSuite.py b/product/ERP5Type/tests/ERP5TypeTestSuite.py
index e5303c0946be91e5d51f4cbaf63fb6ea055c556e..84f1f5ee6da3ce5e3360a6219819ae3ad23170ae 100644
--- a/product/ERP5Type/tests/ERP5TypeTestSuite.py
+++ b/product/ERP5Type/tests/ERP5TypeTestSuite.py
@@ -48,7 +48,7 @@ class ERP5TypeTestSuite(TestSuite):
+ ('--verbose', '--erp5_sql_connection_string=' + mysql_db_list[0]) \
+ args
status_dict = self.spawn(*args, **kw)
- except SubprocessError, e:
+ except SubprocessError as e:
status_dict = e.status_dict
test_log = status_dict['stderr']
search = self.RUN_RE.search(test_log)
diff --git a/product/ERP5Type/tests/ProcessingNodeTestCase.py b/product/ERP5Type/tests/ProcessingNodeTestCase.py
index 890a338898d230e944f007cf6a148005276f1c78..c041d0fd387635d4201df685ad0912a528347cd5 100644
--- a/product/ERP5Type/tests/ProcessingNodeTestCase.py
+++ b/product/ERP5Type/tests/ProcessingNodeTestCase.py
@@ -146,14 +146,14 @@ class ProcessingNodeTestCase(ZopeTestCase.TestCase):
hs.server_protocol, hs.server_name, hs.server_port))
try:
hs = createZServer(log)
- except RuntimeError, e:
+ except RuntimeError as e:
ZopeTestCase._print(str(e))
else:
utils._Z2HOST, utils._Z2PORT = hs.server_name, hs.server_port
_print(hs)
try:
_print(createZServer(log, zserver_type='webdav'))
- except RuntimeError, e:
+ except RuntimeError as e:
ZopeTestCase._print('Could not start webdav zserver: %s\n' % e)
t = Thread(target=Lifetime.loop)
t.setDaemon(1)
@@ -251,7 +251,7 @@ class ProcessingNodeTestCase(ZopeTestCase.TestCase):
error_message = 'tic is looping forever. '
try:
self.assertNoPendingMessage()
- except AssertionError, e:
+ except AssertionError as e:
error_message += str(e)
raise RuntimeError(error_message)
# This give some time between messages
diff --git a/product/ERP5Type/tests/runFunctionalTest.py b/product/ERP5Type/tests/runFunctionalTest.py
index f090f599877555a562b4aeb058b20dc2e4b92656..f043afd1c0af15140ed94bcd3e835ba172779044 100644
--- a/product/ERP5Type/tests/runFunctionalTest.py
+++ b/product/ERP5Type/tests/runFunctionalTest.py
@@ -93,7 +93,7 @@ class FunctionalTestRunner:
"portal_name=", "run_only=", "user=",
"password=", "alarms=",
"email_subject=", "smtp_host=", "xvfb_display="] )
- except getopt.GetoptError, msg:
+ except getopt.GetoptError as msg:
self.usage(sys.stderr, msg)
sys.exit(2)
@@ -273,7 +273,7 @@ user_pref("capability.principal.codebase.p1.subjectName", "");""" % \
try:
status = self.openUrl('%s/portal_tests/TestTool_getResults'
% (self.portal_url))
- except urllib2.HTTPError, e:
+ except urllib2.HTTPError as e:
if e.msg == "No Content" :
status = ""
else:
diff --git a/product/ERP5Type/tests/runUnitTest.py b/product/ERP5Type/tests/runUnitTest.py
index 3967f64fc3bbd5047ce719caa31cdee6803d3d5c..67e6a6e74cf1d80298cafdddbdd3337a01b8e6c8 100755
--- a/product/ERP5Type/tests/runUnitTest.py
+++ b/product/ERP5Type/tests/runUnitTest.py
@@ -740,7 +740,7 @@ def main(argument_list=None):
"sys_path=",
"instance_home=",
])
- except getopt.GetoptError, msg:
+ except getopt.GetoptError as msg:
usage(sys.stderr, msg)
sys.exit(2)
diff --git a/product/ERP5Type/tests/utils.py b/product/ERP5Type/tests/utils.py
index a41626d79dc2c3e97d1da9dc6b9f7985cc8de090..57f7f536c23bf43a96e21dfbe7385c893ec8c774 100644
--- a/product/ERP5Type/tests/utils.py
+++ b/product/ERP5Type/tests/utils.py
@@ -157,7 +157,7 @@ class DummyLocalizer:
def __getitem__(self, key):
if hasattr(self, key):
return getattr(self, key)
- raise KeyError, key
+ raise KeyError(key)
def get_default_language(self):
return self._default_language
@@ -343,7 +343,7 @@ def createZServer(log=os.devnull, zserver_type='http'):
hs.__init__(ip, port, resolver=None, logger_object=lg)
hs.install_handler(zhandler_class(module='Zope2', uri_base=''))
return hs
- except socket.error, e:
+ except socket.error as e:
if e[0] != errno.EADDRINUSE:
raise
hs.close()
@@ -426,7 +426,7 @@ class LogInterceptor:
def _catch_log_errors(self, ignored_level=zLOG.WARNING, subsystem=''):
if subsystem in self.installed:
- raise ValueError, 'Already installed filter!'
+ raise ValueError('Already installed filter!')
root_logger = logging.getLogger(subsystem)
self.installed += (subsystem,)
@@ -583,7 +583,7 @@ def updateCellList(portal, line, cell_type, cell_range_method, cell_dict_list):
elif isinstance(table[0][0], (tuple, list)):
dimension = 3
else:
- raise RuntimeError, "Unsupported table structure!"
+ raise RuntimeError("Unsupported table structure!")
if dimension==1:
for table_line in table:
diff --git a/product/ERP5VCS/Git.py b/product/ERP5VCS/Git.py
index 84605fd330e6303aff00dd90f7c05b9f46469cba..c7ca12c9cb1a2351ba0c89706dbabb5678d1d5ce 100644
--- a/product/ERP5VCS/Git.py
+++ b/product/ERP5VCS/Git.py
@@ -67,7 +67,7 @@ class Git(WorkingCopy):
argv = ['git']
try:
return subprocess.Popen(argv + list(args), **kw)
- except OSError, e:
+ except OSError as e:
import sys
from zLOG import LOG, WARNING
LOG('Git', WARNING,
@@ -118,7 +118,7 @@ class Git(WorkingCopy):
env.update(ERP5_GIT_USERNAME=userpwd[0], ERP5_GIT_PASSWORD=userpwd[1])
try:
return self.git(*args, **kw)
- except GitError, e:
+ except GitError as e:
message = 'Authentication failed'
if message in str(e):
raise GitLoginError(userpwd and message or
@@ -149,7 +149,7 @@ class Git(WorkingCopy):
local, remote = self.git('rev-parse', '--symbolic-full-name',
'HEAD', '@{u}').splitlines()
remote = remote[:13] == 'refs/remotes/' and remote[13:] or None
- except GitError, e:
+ except GitError as e:
local = e.stdout.splitlines()[0]
remote = None
if local != 'HEAD':
@@ -294,7 +294,7 @@ class Git(WorkingCopy):
try:
return self.git('show', 'HEAD:' + self.prefix + path,
strip=False, cwd=self.toplevel)
- except GitError, e:
+ except GitError as e:
err = e.args[0]
if ' does not exist in ' in err or ' exists on disk, but not in ' in err:
raise NotVersionedError(path)
@@ -353,7 +353,7 @@ class Git(WorkingCopy):
push_args = 'push', '--porcelain', remote, '%s:%s' % (src, dst)
try:
self.remote_git(*push_args)
- except GitError, e:
+ except GitError as e:
# first check why we could not push
status = [x for x in e.stdout.splitlines() if x[:1] == '!']
if (len(status) != 1 or
@@ -368,7 +368,7 @@ class Git(WorkingCopy):
# TODO: solve conflicts on */bt/revision automatically
try:
self.git(merge, '@{u}', env=env)
- except GitError, e:
+ except GitError as e:
# XXX: how to know how it failed ?
try:
self.git(merge, '--abort')
@@ -380,7 +380,7 @@ class Git(WorkingCopy):
reset += 1
# retry to push everything
self.remote_git(*push_args)
- except (GitError, GitLoginError), e:
+ except (GitError, GitLoginError) as e:
self.git('reset', '--soft', '@{%u}' % reset)
if isinstance(e, GitLoginError):
raise
diff --git a/product/ERP5VCS/Subversion.py b/product/ERP5VCS/Subversion.py
index 8bce310643e721e4a4882e89d1ea0a2f8b8fe32e..fb15cbf00d7e83b029e998573e7d00eaab124cf0 100644
--- a/product/ERP5VCS/Subversion.py
+++ b/product/ERP5VCS/Subversion.py
@@ -148,7 +148,7 @@ class Subversion(WorkingCopy):
try:
return self._getClient().cat(os.path.join(self.working_copy, path),
Revision(opt_revision_kind.base))
- except ClientError, e:
+ except ClientError as e:
if e.args[1][-1][1] in (errno.ENOENT, svn_err.entry_not_found):
raise NotVersionedError(path)
raise
diff --git a/product/ERP5VCS/SubversionClient.py b/product/ERP5VCS/SubversionClient.py
index a170b7a72f87e32aa290aaac8480ea9d5fd5ff4f..762d3a1312681b8ef116c6c262c5a404bde34bd5 100644
--- a/product/ERP5VCS/SubversionClient.py
+++ b/product/ERP5VCS/SubversionClient.py
@@ -124,7 +124,7 @@ try:
def __call__(self):
current_time = time.time()
if current_time - self.client.creation_time > self.client.getTimeout():
- raise SubversionTimeoutError, 'too long transaction'
+ raise SubversionTimeoutError('too long transaction')
#return True
return False
@@ -273,7 +273,7 @@ try:
return Revision(self.client.checkin(path,
log_message=log_message or 'none',
recurse=recurse))
- except pysvn.ClientError, error:
+ except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep
@@ -283,7 +283,7 @@ try:
def update(self, path):
try:
return [Revision(x) for x in self.client.update(path)]
- except pysvn.ClientError, error:
+ except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep
@@ -295,7 +295,7 @@ try:
# Zope, convert the objects.
try:
status_list = [Status(x) for x in self.client.status(path=path, **kw)]
- except pysvn.ClientError, error:
+ except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep
@@ -330,7 +330,7 @@ try:
def log(self, path):
try:
log_list = self.client.log(path)
- except pysvn.ClientError, error:
+ except pysvn.ClientError as error:
if 'path not found' in error.args[0]:
return
excep = self.getException()
@@ -357,20 +357,20 @@ try:
def info(self, path):
if not os.path.exists(path):
- raise ValueError, "Repository %s does not exist" % path
+ raise ValueError("Repository %s does not exist" % path)
# symlinks are not well supported by pysvn
if os.path.islink(path):
path = os.path.realpath(path)
try:
entry = self.client.info(path=path)
- except pysvn.ClientError, error:
+ except pysvn.ClientError as error:
excep = self.getException()
if excep:
raise excep
else:
raise error
if entry is None:
- raise ValueError, "Could not open SVN repository %s" % path
+ raise ValueError("Could not open SVN repository %s" % path)
# transform entry to dict to make it more usable in zope
members_tuple = ('url', 'uuid', 'revision', 'kind', \
'commit_author', 'commit_revision', 'commit_time',)
@@ -383,7 +383,7 @@ try:
def ls(self, path):
try:
dict_list = self.client.ls(url_or_path=path, recurse=False)
- except pysvn.ClientError, error:
+ except pysvn.ClientError as error:
if 'non-existent' in error.args[0]:
return
excep = self.getException()
@@ -415,4 +415,4 @@ except ImportError:
'could not import pysvn; until pysvn is installed properly,'
' this tool will not work.', error=sys.exc_info())
def newSubversionClient(container, **kw):
- raise SubversionInstallationError, 'pysvn library is not installed'
+ raise SubversionInstallationError('pysvn library is not installed')
diff --git a/product/ERP5VCS/WorkingCopy.py b/product/ERP5VCS/WorkingCopy.py
index f7dc72bc5c356e74b58c39bd99a245b39c7828d2..7252d284397a8511536ca39bb675a11c9388a916 100644
--- a/product/ERP5VCS/WorkingCopy.py
+++ b/product/ERP5VCS/WorkingCopy.py
@@ -269,7 +269,7 @@ class WorkingCopy(Implicit):
try:
with open(os.path.join(self.working_copy, path), 'rU') as f:
text = f.read()
- except IOError, e:
+ except IOError as e:
if e.errno == errno.EISDIR:
return '%s
%r is a folder!' % (head, path)
if e.errno != errno.ENOENT:
@@ -361,7 +361,7 @@ class BusinessTemplateWorkingCopy(BusinessTemplateFolder):
try:
try:
file = open(path, 'r+b')
- except IOError, e:
+ except IOError as e:
if e.errno == errno.EISDIR:
shutil.rmtree(path, ignore_errors=True)
elif e.errno != errno.ENOENT:
diff --git a/product/ERP5Wizard/Tool/WizardTool.py b/product/ERP5Wizard/Tool/WizardTool.py
index 476a9cf9243e11c9c428c5789ed0669f3f111bb7..45ff6b07a03202ee85ee1a960c67482aad01b736 100644
--- a/product/ERP5Wizard/Tool/WizardTool.py
+++ b/product/ERP5Wizard/Tool/WizardTool.py
@@ -455,7 +455,7 @@ class WizardTool(BaseTool):
try:
method = getattr(witch_tool, distant_method)
html = method(parameter_dict)
- except socket.error, message:
+ except socket.error as message:
html = _generateErrorXML("""Cannot contact the server: %s.
Please check your network settings.""" %
server_url)
@@ -464,7 +464,7 @@ class WizardTool(BaseTool):
"data": html,
"next": None,
"previous": None})
- except xmlrpclib.ProtocolError, message:
+ except xmlrpclib.ProtocolError as message:
html = _generateErrorXML("""The server %s refused to reply.
Please contact erp5-dev@erp5.org""" %
server_url)
@@ -473,7 +473,7 @@ class WizardTool(BaseTool):
"data": html,
"next": None,
"previous": None})
- except xmlrpclib.Fault, message:
+ except xmlrpclib.Fault as message:
html = _generateErrorXML("Error/bug inside the server: %s." %server_url)
zLOG.LOG('Wizard Tool xmlrpc fault', zLOG.ERROR, message)
result_call.update({"command": "show",
diff --git a/product/ERP5eGovSecurity/EGOVGroupManager.py b/product/ERP5eGovSecurity/EGOVGroupManager.py
index 8519f7be763cc5c946ee3f87237c63452ac7f6e7..9885287c3169e39fd3a150cbf62f27205ba23a30 100644
--- a/product/ERP5eGovSecurity/EGOVGroupManager.py
+++ b/product/ERP5eGovSecurity/EGOVGroupManager.py
@@ -130,9 +130,9 @@ class EGOVGroupManager(ERP5GroupManager):
if len(catalog_result) != 1: # we won't proceed with groups
if len(catalog_result) > 1: # configuration is screwed
- raise ConsistencyError, 'There is more than one Person whose \
+ raise ConsistencyError('There is more than one Person whose \
login is %s : %s' % (user_name,
- repr([r.getObject() for r in catalog_result]))
+ repr([r.getObject() for r in catalog_result])))
else: # no person is linked to this user login
portal = self.getPortalObject()
diff --git a/product/Formulator/Field.py b/product/Formulator/Field.py
index b3140fb675bbda60d0d9aacf10c376691b8b0191..6caa1d69fdbd72667f9f857a055792b9abb10c40 100644
--- a/product/Formulator/Field.py
+++ b/product/Formulator/Field.py
@@ -505,7 +505,7 @@ class ZMIField(
try:
# validate the form and get results
result = self.form.validate(REQUEST)
- except ValidationError, err:
+ except ValidationError as err:
if REQUEST:
message = "Error: %s - %s" % (err.field.get_value('title'),
err.error_text)
@@ -587,7 +587,7 @@ class ZMIField(
try:
# validate the form and get results
result = self.override_form.validate(REQUEST)
- except ValidationError, err:
+ except ValidationError as err:
if REQUEST:
message = "Error: %s - %s" % (err.field.get_value('title'),
err.error_text)
@@ -620,7 +620,7 @@ class ZMIField(
try:
# validate the form and get results
result = self.tales_form.validate(REQUEST)
- except ValidationError, err:
+ except ValidationError as err:
if REQUEST:
message = "Error: %s - %s" % (err.field.get_value('title'),
err.error_text)
diff --git a/product/Formulator/Form.py b/product/Formulator/Form.py
index 36bee8d1cd25876a9ab07c66f042092d6ef2ba74..a568ace4a3b3980a3c606bc1734db0007edc1212 100644
--- a/product/Formulator/Form.py
+++ b/product/Formulator/Form.py
@@ -381,7 +381,7 @@ class Form:
alternate_name = field.get_value('alternate_name')
if alternate_name:
result[alternate_name] = value
- except ValidationError, err:
+ except ValidationError as err:
errors.append(err)
if len(errors) > 0:
raise FormValidationError(errors, result)
@@ -394,7 +394,7 @@ class Form:
"""
try:
result = self.validate_all(REQUEST, key_prefix=key_prefix)
- except FormValidationError, e:
+ except FormValidationError as e:
# put whatever result we have in REQUEST
for key, value in e.result.items():
REQUEST.set(key, value)
@@ -681,19 +681,19 @@ class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form):
FIXME: hack that could be removed once Zope 2.4.x
goes back to a useful semantics..."""
try: self._checkId(new_id)
- except: raise CopyError, MessageDialog(
+ except: raise CopyError(MessageDialog(
title='Invalid Id',
message=sys.exc_info()[1],
- action ='manage_main')
+ action ='manage_main'))
ob=self._getOb(id)
if not ob.cb_isMoveable():
- raise CopyError, eNotSupported % id
+ raise CopyError(eNotSupported % id)
self._verifyObjectPaste(ob)
try: ob._notifyOfCopyTo(self, op=1)
- except: raise CopyError, MessageDialog(
+ except: raise CopyError(MessageDialog(
title='Rename Error',
message=sys.exc_info()[1],
- action ='manage_main')
+ action ='manage_main'))
self._delObject(id)
ob = aq_base(ob)
ob._setId(new_id)
@@ -728,7 +728,7 @@ class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form):
"""
field = self._getOb(id, None)
if field is None or not hasattr(aq_base(field), 'is_field'):
- raise AttributeError, "No field %s" % id
+ raise AttributeError("No field %s" % id)
if include_disabled or field.get_value('enabled'):
return field
raise FieldDisabledError("Field %s disabled" % id, field)
@@ -783,7 +783,7 @@ class ZMIForm(ObjectManager, PropertyManager, RoleManager, Item, Form):
"""
try:
result = self.settings_form.validate_all(REQUEST)
- except FormValidationError, e:
+ except FormValidationError as e:
message = "Validation error(s).
" + string.join(
map(lambda error: "%s: %s" % (error.field.get_value('title'),
error.error_text), e.errors), "
")
diff --git a/product/Formulator/ProductForm.py b/product/Formulator/ProductForm.py
index 35dc513e0662ad6cb8a23ba91ffb0dcda118d82c..0a149281289c4acca6de540cdcabd4610d755d78 100644
--- a/product/Formulator/ProductForm.py
+++ b/product/Formulator/ProductForm.py
@@ -114,7 +114,7 @@ class ProductForm(BasicForm):
try:
result=self.validate_all(REQUEST)
- except FormValidationError, e:
+ except FormValidationError as e:
for error in e.errors:
errors[error.field.get_value('title')]=error.error_text
diff --git a/product/Formulator/Validator.py b/product/Formulator/Validator.py
index e87ceb899fd065607d9f0365594396eca1723543..15a6eea5320dd23dfca8ec452b0f20ef0e068b67 100644
--- a/product/Formulator/Validator.py
+++ b/product/Formulator/Validator.py
@@ -97,9 +97,9 @@ class StringBaseValidator(Validator):
value = REQUEST.get(key, REQUEST.get('default_%s' % (key, )))
if value is None:
if field.get_value('required'):
- raise Exception, 'Required field %s has not been transmitted. Check that all required fields are in visible groups.' % (repr(field.id), )
+ raise Exception('Required field %s has not been transmitted. Check that all required fields are in visible groups.' % (repr(field.id), ))
else:
- raise KeyError, 'Field %s is not present in request object.' % (repr(field.id), )
+ raise KeyError('Field %s is not present in request object.' % (repr(field.id), ))
if isinstance(value, str):
if field.has_value('whitespace_preserve'):
if not field.get_value('whitespace_preserve'):
@@ -537,7 +537,7 @@ class MultiSelectionValidator(Validator):
def validate(self, field, key, REQUEST):
if REQUEST.get('default_%s' % (key, )) is None:
- raise KeyError, 'Field %s is not present in request object (marker field default_%s not found).' % (repr(field.id), key)
+ raise KeyError('Field %s is not present in request object (marker field default_%s not found).' % (repr(field.id), key))
values = REQUEST.get(key, [])
# NOTE: a hack to deal with single item selections
if not isinstance(values, list):
diff --git a/product/Formulator/tests/testFormValidator.py b/product/Formulator/tests/testFormValidator.py
index 3e50fead47f42e2dcd926c311305fea351da49bb..259709511813728d9b7cea8e772abafde7c03cb8 100644
--- a/product/Formulator/tests/testFormValidator.py
+++ b/product/Formulator/tests/testFormValidator.py
@@ -28,7 +28,7 @@ class ValidatorTestCase(unittest.TestCase):
def assertValidatorRaises(self, exception, error_key, f, *args, **kw):
try:
apply(f, args, kw)
- except exception, e:
+ except exception as e:
if hasattr(e, 'error_key') and e.error_key != error_key:
self.fail('Got wrong error. Expected %s received %s' %
(error_key, e))
diff --git a/product/Formulator/tests/testSerializeForm.py b/product/Formulator/tests/testSerializeForm.py
index 1df549d5ddc1dd5d0d561914bf892f8af78278f4..c76b0eef04fa11b841157e4e1f61361f692d0489 100644
--- a/product/Formulator/tests/testSerializeForm.py
+++ b/product/Formulator/tests/testSerializeForm.py
@@ -210,14 +210,14 @@ class SerializeTestCase(unittest.TestCase):
try:
form.validate_all(request)
self.fail('form should fail in validation')
- except FormValidationError, e:
+ except FormValidationError as e:
self.assertEqual(1, len(e.errors))
text1 = e.errors[0].error_text
try:
form2.validate_all(request)
self.fail('form2 should fail in validation')
- except FormValidationError, e:
+ except FormValidationError as e:
self.assertEqual(1, len(e.errors))
text2 = e.errors[0].error_text
@@ -343,7 +343,7 @@ class SerializeTestCase(unittest.TestCase):
})
empty_field.manage_edit(REQUEST=request)
- except ValidationError, e:
+ except ValidationError as e:
self.fail('error when editing field %s; error message: %s' %
(e.field_id, e.error_text) )
@@ -399,14 +399,14 @@ class SerializeTestCase(unittest.TestCase):
request['field_empty_field'] = ''
try:
result1 = form.validate_all(request)
- except FormValidationError, e:
+ except FormValidationError as e:
# XXX only render first error ...
self.fail('error when editing form1, field %s; error message: %s' %
(e.errors[0].field_id, e.errors[0].error_text) )
try:
result2 = form2.validate_all(request)
- except FormValidationError, e:
+ except FormValidationError as e:
# XXX only render first error ...
self.fail('error when editing form1, field %s; error message: %s' %
(e.errors[0].field_id, e.errors[0].error_text) )
diff --git a/product/HBTreeFolder2/HBTreeFolder2.py b/product/HBTreeFolder2/HBTreeFolder2.py
index 0f03e4e5d895022eac3381445e368c275dcbbbdd..b85bff4bbde3caf65c89bfd0b46bf247fcbdb336 100644
--- a/product/HBTreeFolder2/HBTreeFolder2.py
+++ b/product/HBTreeFolder2/HBTreeFolder2.py
@@ -449,7 +449,7 @@ class HBTreeFolder2Base (Persistent):
def _checkId(self, id, allow_dup=0):
if not allow_dup and self.has_key(id):
- raise BadRequestException, ('The id "%s" is invalid--'
+ raise BadRequestException('The id "%s" is invalid--'
'it is already in use.' % id)
@@ -485,7 +485,7 @@ class HBTreeFolder2Base (Persistent):
object = self._getOb(id)
try:
object.manage_beforeDelete(object, self)
- except BeforeDeleteException, ob:
+ except BeforeDeleteException as ob:
raise
except ConflictError:
raise
diff --git a/product/Localizer/GettextTag.py b/product/Localizer/GettextTag.py
index 89914bcc457ef259dfd973022153ad3092f4d2e1..1b70279f8ea132a2303d643a11cf9cf7fb2bd9b6 100644
--- a/product/Localizer/GettextTag.py
+++ b/product/Localizer/GettextTag.py
@@ -41,7 +41,7 @@ def name_or_expr(mapping, name_attr, expr_attr, default):
return Eval(expr)
if expr is None:
return name
- raise ParseError, ('%s and %s given' % (name_attr, expr_attr), 'calendar')
+ raise ParseError('%s and %s given' % (name_attr, expr_attr), 'calendar')
diff --git a/product/Localizer/MessageCatalog.py b/product/Localizer/MessageCatalog.py
index 360e7c28d1375b9e202ba1c84c41e3984d9085e9..db9c205f9e18319474dd0316771dffa6a4ffdc47 100644
--- a/product/Localizer/MessageCatalog.py
+++ b/product/Localizer/MessageCatalog.py
@@ -739,7 +739,7 @@ class POFile(SimpleItem):
def PUT(self, REQUEST, RESPONSE):
""" """
if REQUEST.environ['REQUEST_METHOD'] != 'PUT':
- raise Forbidden, 'REQUEST_METHOD should be PUT.'
+ raise Forbidden('REQUEST_METHOD should be PUT.')
body = REQUEST['BODY']
self.po_import(self.id, body)
RESPONSE.setStatus(204)
diff --git a/product/Localizer/__init__.py b/product/Localizer/__init__.py
index d13417c44302bd8de4422960492a6c05efb02eb9..0edc7c8374830f4ea25571a840ed127eee9fd24e 100644
--- a/product/Localizer/__init__.py
+++ b/product/Localizer/__init__.py
@@ -44,7 +44,7 @@ def initialize(context):
message = (
"The Localizer product must be installed within the 'Products'"
" folder with the name 'Localizer' (not '%s').") % filename
- raise RuntimeError, message
+ raise RuntimeError(message)
# XXX This code has been written by Cornel Nitu, it may be a solution to
# upgrade instances.
diff --git a/product/MailTemplates/MailTemplate.py b/product/MailTemplates/MailTemplate.py
index 076e33bd30eb77f2190227714198afe2142909f8..29c7c880b09866819fec7a12c90138398fb22430 100644
--- a/product/MailTemplates/MailTemplate.py
+++ b/product/MailTemplates/MailTemplate.py
@@ -40,7 +40,7 @@ class MailTemplate(BaseMailTemplate,ZopePageTemplate):
def pt_editAction(self, REQUEST, mailhost, text, content_type, expand):
"""Change the mailhost and document."""
if self.wl_isLocked():
- raise ResourceLockedError, "File is locked via WebDAV"
+ raise ResourceLockedError("File is locked via WebDAV")
self.expand=expand
self._setPropValue('mailhost',mailhost)
self.pt_edit(text, content_type)
diff --git a/product/MailTemplates/tests/test_FSMailTemplate.py b/product/MailTemplates/tests/test_FSMailTemplate.py
index e350f1a19b16c349221eb44350cf19dc91a6e56d..fffae00d25ec7ee1761eeb6ae35c889b0c7d5654 100644
--- a/product/MailTemplates/tests/test_FSMailTemplate.py
+++ b/product/MailTemplates/tests/test_FSMailTemplate.py
@@ -126,7 +126,7 @@ else:
from zExceptions import Redirect
try:
self.assertRaises(self.ob.fake_skin.test.manage_workspace(self.r))
- except Redirect,r:
+ except Redirect as r:
# this may appear to be incorrect, but http://foo/test_mt
# is what we set as REQUEST['URL1']
self.assertEqual(r.args,('http://foo/test_mt/manage_main',))
diff --git a/product/MailTemplates/tests/test_MailTemplate.py b/product/MailTemplates/tests/test_MailTemplate.py
index 1796481927f388d6b85b3111644eed338b0aaacc..279f2202578636a102d386626db9a52606544409 100644
--- a/product/MailTemplates/tests/test_MailTemplate.py
+++ b/product/MailTemplates/tests/test_MailTemplate.py
@@ -325,7 +325,7 @@ class TestMailTemplate(TestCase):
from zExceptions import Redirect
try:
self.assertRaises(self.mt.manage_workspace(self.r))
- except Redirect,r:
+ except Redirect as r:
# this may appear to be incorrect, but http://foo/test_mt
# is what we set as REQUEST['URL1']
self.assertEqual(r.args,('http://foo/test_mt/pt_editForm',))
@@ -378,7 +378,7 @@ class TestMailTemplate(TestCase):
self.test_add('Test Body')
try:
self.mt.send(**params)
- except TypeError,e:
+ except TypeError as e:
self.assertEqual(e.args[0],error)
else:
self.fail('Mail sent even though params missing')
diff --git a/product/PortalTransforms/Transform.py b/product/PortalTransforms/Transform.py
index 0552dd32a2411275b6c2abd3c5ae70f6ca527170..39aa71e0ca099ab83e3e71332b93c11291b18aee 100644
--- a/product/PortalTransforms/Transform.py
+++ b/product/PortalTransforms/Transform.py
@@ -26,7 +26,7 @@ def import_from_name(module_name):
try:
for sub in module_name.split('.')[1:]:
m = getattr(m, sub)
- except AttributeError, e:
+ except AttributeError as e:
raise ImportError(str(e))
return m
@@ -148,7 +148,7 @@ class Transform(SimpleItem):
pass
try:
m = import_from_name(self.module)
- except ImportError, err:
+ except ImportError as err:
transform = BrokenTransform(self.id, self.module, err)
msg = "Cannot register transform %s (ImportError), using BrokenTransform: Error\n %s" % (self.id, err)
self.title = 'BROKEN'
@@ -159,7 +159,7 @@ class Transform(SimpleItem):
raise TransformException(msg)
try:
transform = m.register()
- except Exception, err:
+ except Exception as err:
transform = BrokenTransform(self.id, self.module, err)
msg = "Cannot register transform %s, using BrokenTransform: Error\n %s" % (self.id, err)
self.title = 'BROKEN'
diff --git a/product/PortalTransforms/libtransforms/commandtransform.py b/product/PortalTransforms/libtransforms/commandtransform.py
index 39da3f0c6645d6f5bfd98ef321e71c488ae4f7e8..45a225d23ac29625ac99b7a7baebb851ddbacc54 100644
--- a/product/PortalTransforms/libtransforms/commandtransform.py
+++ b/product/PortalTransforms/libtransforms/commandtransform.py
@@ -165,6 +165,6 @@ class subprocesstransform:
stderr=PIPE, close_fds=True)
data_out, data_err = process.communicate(input=data)
if process.returncode:
- raise OSError, data_err
+ raise OSError(data_err)
cache.setData(data_out)
return cache
diff --git a/product/PortalTransforms/libtransforms/utils.py b/product/PortalTransforms/libtransforms/utils.py
index f67aef9c39836a326182fb93f169e19d5cfcf545..2c24deaee12f405653e421cbbc5ee98a92769dec 100644
--- a/product/PortalTransforms/libtransforms/utils.py
+++ b/product/PortalTransforms/libtransforms/utils.py
@@ -182,10 +182,10 @@ class StrippingParser( SGMLParser ):
for k, v in attrs:
if k.lower().startswith( 'on' ):
- raise IllegalHTML, 'Javascipt event "%s" not allowed.' % k
+ raise IllegalHTML('Javascipt event "%s" not allowed.' % k)
if v.lower().startswith( 'javascript:' ):
- raise IllegalHTML, 'Javascipt URI "%s" not allowed.' % v
+ raise IllegalHTML('Javascipt URI "%s" not allowed.' % v)
self.result = '%s %s="%s"' % (self.result, k, v)
@@ -196,7 +196,7 @@ class StrippingParser( SGMLParser ):
self.result = self.result + ' />'
elif NASTY_TAGS.get( tag ):
- raise IllegalHTML, 'Dynamic tag "%s" not allowed.' % tag
+ raise IllegalHTML('Dynamic tag "%s" not allowed.' % tag)
else:
pass # omit tag
diff --git a/product/PortalTransforms/libtransforms/zope27rest.py b/product/PortalTransforms/libtransforms/zope27rest.py
index cd0175ab955f60a12597c3c0d9a6e36a26b28d73..52c18695713d5251640123651c0e78705ccf994a 100644
--- a/product/PortalTransforms/libtransforms/zope27rest.py
+++ b/product/PortalTransforms/libtransforms/zope27rest.py
@@ -20,15 +20,15 @@ Based on the new implementation of Zope 2.7.1 altered for PortalTransforms
try:
import docutils
except ImportError:
- raise ImportError, 'Please install docutils 0.3.3+ from http://docutils.sourceforge.net/#download.'
+ raise ImportError('Please install docutils 0.3.3+ from http://docutils.sourceforge.net/#download.')
version = docutils.__version__.split('.')
if version < ['0', '3', '3']:
- raise ImportError, """Old version of docutils found:
+ raise ImportError("""Old version of docutils found:
Got: %(version)s, required: 0.3.3+
Please remove docutils from %(path)s and replace it with a new version. You
can download docutils at http://docutils.sourceforge.net/#download.
-""" % {'version' : docutils.__version__, 'path' : docutils.__path__[0] }
+""" % {'version' : docutils.__version__, 'path' : docutils.__path__[0] })
import sys, os, locale
diff --git a/product/PortalTransforms/transforms/__init__.py b/product/PortalTransforms/transforms/__init__.py
index c855f97ae76f7cb8610ff8dca2e85963920244b0..8145555c377a699e637c98bdba968a9be8f05729 100644
--- a/product/PortalTransforms/transforms/__init__.py
+++ b/product/PortalTransforms/transforms/__init__.py
@@ -54,12 +54,12 @@ for m in modules:
try:
ns = __import__(m, g, g, None)
transforms.append(ns.register())
- except ImportError, e:
+ except ImportError as e:
msg = "Problem importing module %s : %s" % (m, e)
log(msg, severity=ERROR)
- except MissingBinary, e:
+ except MissingBinary as e:
log(str(e), severity=DEBUG)
- except Exception, e:
+ except Exception as e:
import traceback
traceback.print_exc()
log("Raised error %s for %s" % (e, m), severity=ERROR)
diff --git a/product/PortalTransforms/transforms/python.py b/product/PortalTransforms/transforms/python.py
index 8a8862fb8ac5eb15131a648052a53672583f39e2..75014b8b4891400af126595a4bd31193b539eae7 100644
--- a/product/PortalTransforms/transforms/python.py
+++ b/product/PortalTransforms/transforms/python.py
@@ -57,7 +57,7 @@ class Parser:
self.out.write('\n')
try:
tokenize.tokenize(text.readline, self)
- except tokenize.TokenError, ex:
+ except tokenize.TokenError as ex:
msg = ex[0]
line = ex[1][0]
self.out.write("" % (
diff --git a/product/PortalTransforms/transforms/safe_html.py b/product/PortalTransforms/transforms/safe_html.py
index 78fc000705ee27119a4e204c67f81e6e994283b6..b32705d339ebf7d60ebb7e393f06b78c4a43009e 100644
--- a/product/PortalTransforms/transforms/safe_html.py
+++ b/product/PortalTransforms/transforms/safe_html.py
@@ -214,13 +214,13 @@ class StrippingParser(HTMLParser):
for k, v in attrs:
if remove_script and k.strip().lower().startswith('on'):
if not self.raise_error: continue
- else: raise IllegalHTML, 'Script event "%s" not allowed.' % k
+ else: raise IllegalHTML('Script event "%s" not allowed.' % k)
elif v is None:
self.result.append(' %s' % k)
elif remove_script and hasScript(v) and \
not (k.lower() == 'src' and tag.lower() == 'img'):
if not self.raise_error: continue
- else: raise IllegalHTML, 'Script URI "%s" not allowed.' % v
+ else: raise IllegalHTML('Script URI "%s" not allowed.' % v)
else:
if tag.lower() == 'meta' and k.lower() == 'content' and \
self.default_encoding and self.default_encoding not in v:
@@ -246,7 +246,7 @@ class StrippingParser(HTMLParser):
elif self.nasty.has_key(tag):
self.suppress = True
if self.raise_error:
- raise IllegalHTML, 'Dynamic tag "%s" not allowed.' % tag
+ raise IllegalHTML('Dynamic tag "%s" not allowed.' % tag)
else:
# omit tag
pass
@@ -440,7 +440,7 @@ class SafeHTML:
remove_javascript=self.config.get('remove_javascript', True),
raise_error=False,
default_encoding=self.config.get('default_encoding', 'utf-8'))
- except IllegalHTML, inst:
+ except IllegalHTML as inst:
data.setData(msg_pat % ("Error", str(inst)))
break
except (HTMLParseError, UnicodeDecodeError):
diff --git a/product/ZLDAPConnection/Entry.py b/product/ZLDAPConnection/Entry.py
index 684bc57919f88abd3c03b0235e43203a99e2cc9f..b41af766f78799541761b7246bc201041caa3e11 100644
--- a/product/ZLDAPConnection/Entry.py
+++ b/product/ZLDAPConnection/Entry.py
@@ -83,7 +83,7 @@ class GenericEntry(Acquisition.Implicit):
def _connection(self):
if self.__connection is None:
- raise ConnectionError, 'No connection object for this entry'
+ raise ConnectionError('No connection object for this entry')
else:
return self.__connection
@@ -99,20 +99,20 @@ class GenericEntry(Acquisition.Implicit):
if conn.hasEntry(key):
return conn.getEntry(key, self)
else:
- raise IndexError, key
+ raise IndexError(key)
def __getattr__(self, attr):
if self._data.has_key(attr):
return AttrWrap(self._data[attr])
else:
- raise AttributeError, attr
+ raise AttributeError(attr)
#### Direct access for setting/getting/unsetting attributes
def get(self, attr):
if self._data.has_key(attr):
return self._data[attr]
else:
- raise AttributeError, attr
+ raise AttributeError(attr)
def set(self, key, value):
""" Sets individual items """
@@ -169,7 +169,7 @@ class GenericEntry(Acquisition.Implicit):
#### Get the ZLDAPConnection object.
def _connection(self):
if self.__connection is None:
- raise ConnectionError, 'Cannot Get Connection'
+ raise ConnectionError('Cannot Get Connection')
else:
return self.__connection
@@ -233,7 +233,7 @@ class GenericEntry(Acquisition.Implicit):
# and verify that it doesn't already exist
dn = "%s,%s" % (string.strip(rdn), self.dn)
if conn.hasEntry(dn): # Check the LDAP server directly
- raise KeyError, "DN '%s' already exists" % dn
+ raise KeyError("DN '%s' already exists" % dn)
# Now split out the first attr based on the RDN (ie 'cn=bob') and
# turn it into one of our attributes (ie attr[cn] = 'bob')
@@ -395,7 +395,7 @@ class TransactionalEntry(GenericEntry): #Acquisition.Implicit
#create the new full DN for new subentry and check its existance
dn='%s,%s' % (string.strip(rdn), self.dn)
if c.hasEntry(dn):
- raise KeyError, "DN '%s' already exists" % dn
+ raise KeyError("DN '%s' already exists" % dn)
# now split out the first attr based on the rdn (ie 'cn=bob', turns
# into attr['cn'] = 'bob'
diff --git a/product/ZLDAPConnection/ZLDAP.py b/product/ZLDAPConnection/ZLDAP.py
index 0ffe451930678523d1d0918a7176e53ea822900e..37c34e53f5eb28ae7dac96e3f5f44fb048e8ec23 100644
--- a/product/ZLDAPConnection/ZLDAP.py
+++ b/product/ZLDAPConnection/ZLDAP.py
@@ -136,8 +136,7 @@ class ZLDAPConnection(
def tpc_begin(self,*ignored):
#make sure we're open!
if not self.__ping(): #we're not open
- raise (ConnectionError,
- 'LDAP Connection is not open for commiting')
+ raise ConnectionError
self._v_okobjects=[]
def commit(self, o, *ignored):
@@ -230,7 +229,7 @@ class ZLDAPConnection(
if getattr(self, '_v_add',{}).has_key(dn):
return (dn, self._v_add[dn]._data)
elif dn in getattr(self,'_v_delete',()):
- raise ldap.NO_SUCH_OBJECT, "Entry '%s' has been deleted" % dn
+ raise ldap.NO_SUCH_OBJECT("Entry '%s' has been deleted" % dn)
try:
e=self._connection().search_s(
@@ -238,7 +237,7 @@ class ZLDAPConnection(
)
if e: return e[0]
except:
- raise ldap.NO_SUCH_OBJECT, "Cannot retrieve entry '%s'" % dn
+ raise ldap.NO_SUCH_OBJECT("Cannot retrieve entry '%s'" % dn)
def getEntry(self, dn, o=None):
@@ -297,7 +296,7 @@ class ZLDAPConnection(
### modifying entries
def _modifyEntry(self, dn, modlist):
if not getattr(self,'_isCommitting',0):
- raise AccessError, 'Cannot modify unless in a commit'
+ raise AccessError('Cannot modify unless in a commit')
#someone's trying to be sneaky and modify an object
#outside of a commit. We're not going to allow that!
c=self._connection()
@@ -321,7 +320,7 @@ class ZLDAPConnection(
def _deleteEntry(self, dn):
if not getattr(self, '_isCommitting',0):
- raise AccessError, 'Cannot delete unless in a commit'
+ raise AccessError('Cannot delete unless in a commit')
c=self._connection()
c.delete_s(dn)
@@ -342,7 +341,7 @@ class ZLDAPConnection(
def _addEntry(self, dn, attrs):
if not getattr(self, '_isCommitting',0):
- raise AccessError, 'Cannot add unless in a commit'
+ raise AccessError('Cannot add unless in a commit')
c=self._connection()
c.add_s(dn, attrs)
@@ -364,7 +363,7 @@ class ZLDAPConnection(
if not self.isOpen(): self._open()
return self._v_conn
else:
- raise ConnectionError, 'Connection Closed'
+ raise ConnectionError('Connection Closed')
GetConnection=_connection
@@ -373,7 +372,7 @@ class ZLDAPConnection(
self._open()
return self._v_conn
else:
- raise ConnectionError, 'Connection Closed'
+ raise ConnectionError('Connection Closed')
def isOpen(self):
" quickly checks to see if the connection's open "
diff --git a/product/ZLDAPMethods/LM.py b/product/ZLDAPMethods/LM.py
index 40bdbcbb29e62355d81df88f73b588bc9f6da23d..995304e7152914cb53b2880de87f87b806bf1c63 100644
--- a/product/ZLDAPMethods/LM.py
+++ b/product/ZLDAPMethods/LM.py
@@ -57,20 +57,20 @@ class ERP5LDIFRecordList(LDIFRecordList):
if attr_type=='dn':
# attr type and value pair was DN of LDIF record
if dn!=None:
- raise ValueError, 'Two lines starting with dn: in one record.'
+ raise ValueError('Two lines starting with dn: in one record.')
if not is_dn(attr_value):
- raise ValueError, 'No valid string-representation of distinguished name %s.' % (repr(attr_value))
+ raise ValueError('No valid string-representation of distinguished name %s.' % (repr(attr_value)))
dn = attr_value
elif attr_type=='version' and dn is None:
version = 1
elif attr_type=='changetype':
# attr type and value pair was DN of LDIF record
if dn is None:
- raise ValueError, 'Read changetype: before getting valid dn: line.'
+ raise ValueError('Read changetype: before getting valid dn: line.')
if changetype!=None:
- raise ValueError, 'Two lines starting with changetype: in one record.'
+ raise ValueError('Two lines starting with changetype: in one record.')
if not valid_changetype_dict.has_key(attr_value):
- raise ValueError, 'changetype value %s is invalid.' % (repr(attr_value))
+ raise ValueError('changetype value %s is invalid.' % (repr(attr_value)))
changetype = attr_value
attr_type, attr_value = self._parseAttrTypeandValue()
modify_list = []
diff --git a/product/ZLDAPMethods/ldifvar.py b/product/ZLDAPMethods/ldifvar.py
index 6b0ef0ee8de32c2062bd97cf93854b16a9b6b716..388127ae687e84db6c9fdad3b3ea4eaf8984d50b 100644
--- a/product/ZLDAPMethods/ldifvar.py
+++ b/product/ZLDAPMethods/ldifvar.py
@@ -77,10 +77,10 @@ class LDIFVar:
self.args=args
if not args.has_key('type'):
- raise ParseError, ('the type attribute is required', 'dtvar')
+ raise ParseError('the type attribute is required', 'dtvar')
t=args['type']
if not valid_type(t):
- raise ParseError, ('invalid type, %s' % t, 'dtvar')
+ raise ParseError('invalid type, %s' % t, 'dtvar')
def render(self, md):
name=self.__name__
@@ -95,7 +95,7 @@ class LDIFVar:
return
if type(expr) is not type(''):
raise
- raise ValueError, 'Missing input variable, %s' % name
+ raise ValueError('Missing input variable, %s' % name)
if v is None:
return ''
@@ -110,7 +110,7 @@ class LDIFVar:
except:
if not v and args.has_key('optional') and args['optional']:
return
- raise ValueError, (
+ raise ValueError(
'Invalid integer value for %s' % name)
elif t=='float':
try:
@@ -122,7 +122,7 @@ class LDIFVar:
except:
if not v and args.has_key('optional') and args['optional']:
return
- raise ValueError, (
+ raise ValueError(
'Invalid floating-point value for %s' % name)
else:
@@ -132,7 +132,7 @@ class LDIFVar:
if args.has_key('optional') and args['optional']:
return
else:
- raise ValueError, (
+ raise ValueError(
'Invalid empty string value for %s' % name)
return v
@@ -152,13 +152,13 @@ class LDIFLine:
self.args=args
if not args.has_key('type'):
- raise ParseError, ('the type attribute is required', 'ldifattr')
+ raise ParseError('the type attribute is required', 'ldifattr')
t=args['type']
if not valid_type(t):
- raise ParseError, ('invalid type, %s' % t, 'dtvar')
+ raise ParseError('invalid type, %s' % t, 'dtvar')
if not args.has_key('attr'):
- raise ParseError, ('the attr attribute is required', 'ldifattr')
+ raise ParseError('the attr attribute is required', 'ldifattr')
a=args['attr']
def render(self, md):
@@ -176,13 +176,13 @@ class LDIFLine:
return default
if type(expr) is not type(''):
raise
- raise ValueError, 'Missing input variable, %s' % name
+ raise ValueError('Missing input variable, %s' % name)
if v is None:
if args.has_key('optional') and args['optional']:
return default
else:
- raise ValueError, 'Missing input variable, %s' % name
+ raise ValueError('Missing input variable, %s' % name)
if a in ['',None]:
return default
@@ -196,7 +196,7 @@ class LDIFLine:
except:
if not v and args.has_key('optional') and args['optional']:
return default
- raise ValueError, (
+ raise ValueError(
'Invalid integer value for %s' % name)
elif t=='float':
try:
@@ -208,7 +208,7 @@ class LDIFLine:
except:
if not v and args.has_key('optional') and args['optional']:
return default
- raise ValueError, (
+ raise ValueError(
'Invalid floating-point value for %s' % name)
else:
@@ -218,7 +218,7 @@ class LDIFLine:
if args.has_key('optional') and args['optional']:
return default
else:
- raise ValueError, (
+ raise ValueError(
'Invalid empty string value for %s' % name)
return '%s: %s' % (a, v)
diff --git a/product/ZMySQLDA/DABase.py b/product/ZMySQLDA/DABase.py
index 1ecc6638cd8b270415ecea2ecbd0621662bf44e4..5194f1ba64178c1b2a444460f383490ae6648b53 100644
--- a/product/ZMySQLDA/DABase.py
+++ b/product/ZMySQLDA/DABase.py
@@ -135,7 +135,7 @@ class Connection(Shared.DC.ZRDB.Connection.Connection):
if name=='tableNamed':
if not hasattr(self, '_v_tables'): self.tpValues()
return self._v_tables.__of__(self)
- raise KeyError, name
+ raise KeyError(name)
def manage_wizard(self, tables):
" "
@@ -155,7 +155,7 @@ class TableBrowserCollection(Acquisition.Implicit):
class Browser(Base):
def __getattr__(self, name):
try: return self._d[name]
- except KeyError: raise AttributeError, name
+ except KeyError: raise AttributeError(name)
class values:
@@ -225,7 +225,7 @@ class TableBrowser(Browser, Acquisition.Implicit):
elif d:
values.append(str(d))
else:
- raise ValueError, (
+ raise ValueError(
'no default was given for %s' % n)
diff --git a/product/ZMySQLDA/db.py b/product/ZMySQLDA/db.py
index b2f9e8e38774ce890a47a965331e88bb3332152a..8d2ada5742999548ace1b09deb835f6fd9286220 100644
--- a/product/ZMySQLDA/db.py
+++ b/product/ZMySQLDA/db.py
@@ -97,9 +97,8 @@ MySQLdb_version_required = (0,9,2)
_v = getattr(_mysql, 'version_info', (0,0,0))
if _v < MySQLdb_version_required:
- raise NotSupportedError, \
- "ZMySQLDA requires at least MySQLdb %s, %s found" % \
- (MySQLdb_version_required, _v)
+ raise NotSupportedError("ZMySQLDA requires at least MySQLdb %s, %s found" % \
+ (MySQLdb_version_required, _v))
from MySQLdb.converters import conversions
from MySQLdb.constants import FIELD_TYPE, CR, ER, CLIENT
@@ -222,7 +221,7 @@ class DB(TM):
if self._try_transactions == '-':
transactional = 0
elif not transactional and self._try_transactions == '+':
- raise NotSupportedError, "transactions not supported by this server"
+ raise NotSupportedError("transactions not supported by this server")
self._transactions = transactional
self._use_TM = transactional or self._mysql_lock
@@ -353,7 +352,7 @@ class DB(TM):
"""
try:
self.db.query(query)
- except OperationalError, m:
+ except OperationalError as m:
if m[0] in query_syntax_error:
raise OperationalError(m[0], '%s: %s' % (m[1], query))
if m[0] in lock_error:
@@ -365,7 +364,7 @@ class DB(TM):
# Hm. maybe the db is hosed. Let's restart it.
self._forceReconnection()
self.db.query(query)
- except ProgrammingError, exception:
+ except ProgrammingError as exception:
LOG('ZMySQLDA', ERROR, 'query failed: %s' % (query,))
# XXX sometimes, after a programming error, the database object
# gets fully broken and non-functional. So recover it by
@@ -476,7 +475,7 @@ class DB(TM):
self._query("ROLLBACK")
else:
LOG('ZMySQLDA', ERROR, "aborting when non-transactional")
- except OperationalError, m:
+ except OperationalError as m:
LOG('ZMySQLDA', ERROR, "exception during _abort",
error=sys.exc_info())
if m[0] not in hosed_connection:
@@ -531,7 +530,7 @@ class DB(TM):
with (nested if src__ else self.lock)():
try:
old_list, old_set, old_default = self._getTableSchema(name)
- except ProgrammingError, e:
+ except ProgrammingError as e:
if e[0] != ER.NO_SUCH_TABLE or not create_if_not_exists:
raise
if not src__:
diff --git a/product/ZMySQLDA/tests/testDeferredConnection.py b/product/ZMySQLDA/tests/testDeferredConnection.py
index 69f0e73cc7f37e7678804d0e3446be707c882287..a91de422254db21607543276abd57b48906cc5eb 100644
--- a/product/ZMySQLDA/tests/testDeferredConnection.py
+++ b/product/ZMySQLDA/tests/testDeferredConnection.py
@@ -55,7 +55,7 @@ def fake_db_query(self, *args, **kw):
"""
global GLOBAL_DB_CONNECTED_FLAG
if GLOBAL_DB_CONNECTED_FLAG == UNCONNECTED_STATE:
- raise OperationalError, (hosed_connection[0], 'dummy exception')
+ raise OperationalError(hosed_connection[0], 'dummy exception')
return self.original_query(*args, **kw)
class TestDeferredConnection(ERP5TypeTestCase):
@@ -136,7 +136,7 @@ class TestDeferredConnection(ERP5TypeTestCase):
try:
try:
self.commit()
- except OperationalError, m:
+ except OperationalError as m:
if m[0] not in hosed_connection:
raise
else:
diff --git a/product/ZSQLCatalog/ColumnMap.py b/product/ZSQLCatalog/ColumnMap.py
index 4f671a3f286b77af3f95c9d7842c824aca837faf..3c1027ea0cb42a7f239fc4630211b6dfa7b677f8 100644
--- a/product/ZSQLCatalog/ColumnMap.py
+++ b/product/ZSQLCatalog/ColumnMap.py
@@ -194,7 +194,7 @@ class ColumnMap(object):
if alias is not None:
self.resolveTable(table_name, alias, group=group)
elif alias is not None and alias != existing_value:
- raise ValueError, 'Table %r for group %r is aliased as %r, can\'t alias it now as %r' % (table_name, group, existing_value, alias)
+ raise ValueError('Table %r for group %r is aliased as %r, can\'t alias it now as %r' % (table_name, group, existing_value, alias))
def _mapColumns(self, column_table_map, table_usage_dict, column_name_set, group, vote_result_dict):
mapping_dict = {}
@@ -287,7 +287,7 @@ class ColumnMap(object):
# Detect incomplete mappings
if len(column_name_set):
- raise ValueError, 'Could not map those columns: %r' % (column_name_set, )
+ raise ValueError('Could not map those columns: %r' % (column_name_set, ))
# Do the actual mapping
for column_name, table_name in mapping_dict.iteritems():
@@ -506,7 +506,7 @@ class ColumnMap(object):
if column == 'uid':
LOG('ColumnMap', WARNING, 'Attempt to remap uid from %r to %r ignored.' % (previous_value, table_name))
else:
- raise ValueError, 'Cannot remap a column to another table. column_map[%r] = %r, new = %r' % (column_map_key, column_map.get(column_map_key), table_name)
+ raise ValueError('Cannot remap a column to another table. column_map[%r] = %r, new = %r' % (column_map_key, column_map.get(column_map_key), table_name))
def resolveTable(self, table_name, alias, group=DEFAULT_GROUP_ID):
table_alias_key = (group, table_name)
diff --git a/product/ZSQLCatalog/Extensions/zsqlbrain.py b/product/ZSQLCatalog/Extensions/zsqlbrain.py
index 325a1d5a06941a588f9484863e9c5e05f40d732c..f9f390219ad5357b8242b2246740f456895db956 100644
--- a/product/ZSQLCatalog/Extensions/zsqlbrain.py
+++ b/product/ZSQLCatalog/Extensions/zsqlbrain.py
@@ -52,8 +52,8 @@ class ZSQLBrain(Acquisition.Implicit):
def getObject(self, REQUEST=None):
"""Try to return the object for this record"""
if 'path' not in dir(self) and 'PATH' not in dir(self):
- raise ValueError, "Unable to getObject from ZSQLBrain if ZSQL Method "\
- "does not retrieves the `path` column from catalog table."
+ raise ValueError("Unable to getObject from ZSQLBrain if ZSQL Method "\
+ "does not retrieves the `path` column from catalog table.")
obj = self.aq_parent.unrestrictedTraverse(self.getPath())
if obj is None:
if REQUEST is None:
diff --git a/product/ZSQLCatalog/Operator/ComparisonOperator.py b/product/ZSQLCatalog/Operator/ComparisonOperator.py
index 30c76d98d43088ab1d6d56e2d1706f75fd0cfb17..262a1be9db12ab79907ced132114f6fb410e66cc 100644
--- a/product/ZSQLCatalog/Operator/ComparisonOperator.py
+++ b/product/ZSQLCatalog/Operator/ComparisonOperator.py
@@ -45,10 +45,10 @@ class ComparisonOperatorBase(OperatorBase):
return SQLExpression(self, where_expression='%s %s %s' % (column, self.getOperator().upper(), value_list))
def render(self, column, value_list):
- raise NotImplementedError, 'This method must be overloaded by a subclass.'
+ raise NotImplementedError('This method must be overloaded by a subclass.')
def renderValue(self, value_list):
- raise NotImplementedError, 'This method must be overloaded by a subclass.'
+ raise NotImplementedError('This method must be overloaded by a subclass.')
verifyClass(IOperator, ComparisonOperatorBase)
@@ -61,7 +61,7 @@ class MonovaluedComparisonOperator(ComparisonOperatorBase):
try:
value_list, = value_list
except ValueError:
- raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list)
+ raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list))
return self._renderValue(value_list)
def render(self, column, value_list):
@@ -72,7 +72,7 @@ class MonovaluedComparisonOperator(ComparisonOperatorBase):
try:
value_list, = value_list
except ValueError:
- raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list)
+ raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list))
return self._render(column, value_list)
verifyClass(IOperator, MonovaluedComparisonOperator)
@@ -83,7 +83,7 @@ class MultivaluedComparisonOperator(ComparisonOperatorBase):
value_list must be a multi-value list (more than one item).
"""
if not isinstance(value_list, list_type_list) or len(value_list) < 2:
- raise ValueError, '%r: value_list must be a list of more than one item. Got %r' % (self, value_list)
+ raise ValueError('%r: value_list must be a list of more than one item. Got %r' % (self, value_list))
return '(%s)' % ', '.join(map(self._renderValue, value_list))
def render(self, column, value_list):
@@ -91,7 +91,7 @@ class MultivaluedComparisonOperator(ComparisonOperatorBase):
value_list must be a multi-value list (more than one item).
"""
if not isinstance(value_list, list_type_list) or len(value_list) < 2:
- raise ValueError, '%r: value_list must be a list of more than one item. Got %r' % (self, value_list)
+ raise ValueError('%r: value_list must be a list of more than one item. Got %r' % (self, value_list))
return column, '(%s)' % ', '.join(map(self._renderValue, value_list))
verifyClass(IOperator, MultivaluedComparisonOperator)
@@ -153,7 +153,7 @@ class MroongaComparisonOperator(MatchComparisonOperator):
try:
value_list, = value_list
except ValueError:
- raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list)
+ raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list))
if self.force_boolean:
fulltext_query = '*D+ %s' % value_list
@@ -192,7 +192,7 @@ class SphinxSEComparisonOperator(MonovaluedComparisonOperator):
try:
value_list, = value_list
except ValueError:
- raise ValueError, '%r: value_list must not contain more than one item. Got %r' % (self, value_list)
+ raise ValueError('%r: value_list must not contain more than one item. Got %r' % (self, value_list))
value_list = '%s;mode=extended2;limit=1000' % value_list
return self._renderValue(value_list)
diff --git a/product/ZSQLCatalog/Operator/OperatorBase.py b/product/ZSQLCatalog/Operator/OperatorBase.py
index 66151d60988bc69d9ec46dfc93bc17bbefdd87b0..6a40352219ef04f6177b58ccba229feac16ab772 100644
--- a/product/ZSQLCatalog/Operator/OperatorBase.py
+++ b/product/ZSQLCatalog/Operator/OperatorBase.py
@@ -151,8 +151,8 @@ class OperatorBase(object):
valueDefaultSearchTextRenderer)(value)
def asSQLExpression(self, column, value_list, only_group_columns):
- raise NotImplementedError, 'This method must be overloaded by a subclass ' \
- 'to be able to get an SQL representation of this operator.'
+ raise NotImplementedError('This method must be overloaded by a subclass ' \
+ 'to be able to get an SQL representation of this operator.')
def __repr__(self):
return '<%s(%r) at %s>' % (self.__class__.__name__, self.getOperator(), id(self))
diff --git a/product/ZSQLCatalog/Query/AutoQuery.py b/product/ZSQLCatalog/Query/AutoQuery.py
index 9dcb104d1ce907cda979f3321d5046fffb75a586..fe6b0011b9c089e60ad5df787745ac9cb275983d 100644
--- a/product/ZSQLCatalog/Query/AutoQuery.py
+++ b/product/ZSQLCatalog/Query/AutoQuery.py
@@ -59,7 +59,7 @@ class AutoQuery(Query):
self.operator = operator
self.ignore_empty_string = kw.pop('ignore_empty_string', True)
if 'key' in kw and len(kw) > 2:
- raise ValueError, '"key" parameter cannot be used when more than one column is given. key=%r' % (kw['key'], )
+ raise ValueError('"key" parameter cannot be used when more than one column is given. key=%r' % (kw['key'], ))
self.search_key = kw.pop('key', None)
def _createWrappedQuery(self, sql_catalog):
@@ -106,7 +106,7 @@ class AutoQuery(Query):
if self.table_alias_list is not None:
query.setTableAliasList(self.table_alias_list)
if query is None:
- raise ValueError, '%r failed generating a query from its parameters.' % (self, )
+ raise ValueError('%r failed generating a query from its parameters.' % (self, ))
self.wrapped_query = query
def _asSearchTextExpression(self, sql_catalog, column=None):
diff --git a/product/ZSQLCatalog/Query/ComplexQuery.py b/product/ZSQLCatalog/Query/ComplexQuery.py
index be99d5d594e11b3a3c991303e010fcf58c16dd39..06b16b97bc4b6ab4b9a3c588c0cddc427ccb1419 100644
--- a/product/ZSQLCatalog/Query/ComplexQuery.py
+++ b/product/ZSQLCatalog/Query/ComplexQuery.py
@@ -158,7 +158,7 @@ class ComplexQuery(Query):
assert len(search_text_list) == 1
result = 'NOT %s' % (search_text_list[0], )
else:
- raise ValueError, 'Unknown operator %r' % (self.logical_operator, )
+ raise ValueError('Unknown operator %r' % (self.logical_operator, ))
if column not in (None, ''):
if self_is_composed:
result = '(%s)' % (result, )
diff --git a/product/ZSQLCatalog/Query/Query.py b/product/ZSQLCatalog/Query/Query.py
index a63f5df79ed1c68fda6bdc0cb22ce956d3bf9f6b..c4e669af5e00324e8c674b9c87eacb2106aff506 100644
--- a/product/ZSQLCatalog/Query/Query.py
+++ b/product/ZSQLCatalog/Query/Query.py
@@ -45,13 +45,13 @@ class Query(object):
"""
To enable SQL rendering, overload this method in a subclass.
"""
- raise TypeError, 'A %s cannot be rendered as an SQL expression.' % (self.__class__.__name__, )
+ raise TypeError('A %s cannot be rendered as an SQL expression.' % (self.__class__.__name__, ))
def _asSearchTextExpression(self, sql_catalog, column=None):
"""
To enable Search Text rendering, overload this method in a subclass.
"""
- raise TypeError, 'A %s cannot be rendered as a SearchText expression.' % (self.__class__.__name__, )
+ raise TypeError('A %s cannot be rendered as a SearchText expression.' % (self.__class__.__name__, ))
def asSearchTextExpression(self, sql_catalog, column=None):
return self._asSearchTextExpression(sql_catalog, column=column)[1]
@@ -60,7 +60,7 @@ class Query(object):
"""
This method must always be overloaded by subclasses.
"""
- raise NotImplementedError, '%s is incompletely implemented.' % (self.__class__.__name__, )
+ raise NotImplementedError('%s is incompletely implemented.' % (self.__class__.__name__, ))
verifyClass(IQuery, Query)
diff --git a/product/ZSQLCatalog/Query/SQLQuery.py b/product/ZSQLCatalog/Query/SQLQuery.py
index 9e30908a4bc6312c771b5fd03302744e7f84c929..5cc7bef35945482a8e7eebdd31621d0c2e7bfba4 100644
--- a/product/ZSQLCatalog/Query/SQLQuery.py
+++ b/product/ZSQLCatalog/Query/SQLQuery.py
@@ -45,7 +45,7 @@ class SQLQuery(Query):
Raw SQL text.
"""
if not isinstance(payload, basestring):
- raise TypeError, 'Payload must be a string, got a %r: %r' % (type(payload), payload)
+ raise TypeError('Payload must be a string, got a %r: %r' % (type(payload), payload))
assert len(payload)
self.payload = '(' + payload + ')'
diff --git a/product/ZSQLCatalog/Query/SimpleQuery.py b/product/ZSQLCatalog/Query/SimpleQuery.py
index dae9d3a6cf3d8a5bf391b381bd1d0b513f2c2660..eeb750a2842ea67a0238f6f429c3778709a4bcd2 100644
--- a/product/ZSQLCatalog/Query/SimpleQuery.py
+++ b/product/ZSQLCatalog/Query/SimpleQuery.py
@@ -66,7 +66,7 @@ class SimpleQuery(Query):
"""
self.search_key = search_key
if len(kw) != 1:
- raise ValueError, 'SimpleQuery can support one and one only column. Got %r.' % (kw, )
+ raise ValueError('SimpleQuery can support one and one only column. Got %r.' % (kw, ))
self.column, value = kw.popitem()
# Usability improvement code (those changes should not be needed when
# this Query is instanciated by a SearchKey, as operator should be correct
@@ -75,7 +75,7 @@ class SimpleQuery(Query):
if comparison_operator == 'in':
if isinstance(value, list_type_list):
if len(value) == 0:
- raise ValueError, 'Empty lists are not allowed.'
+ raise ValueError('Empty lists are not allowed.')
elif len(value) == 1:
value, = value
comparison_operator = '='
@@ -84,7 +84,7 @@ class SimpleQuery(Query):
elif comparison_operator == '=':
if isinstance(value, list_type_list):
if len(value) == 0:
- raise ValueError, 'Empty lists are not allowed.'
+ raise ValueError('Empty lists are not allowed.')
elif len(value) == 1:
value, = value
else:
@@ -97,7 +97,7 @@ class SimpleQuery(Query):
raise ValueError('Unexpected comparison_operator %r for None value.'
% (comparison_operator, ))
elif comparison_operator == 'is':
- raise ValueError, 'Non-None value (%r) with "is" comparison_operator. Not sure what to do.' % (value, )
+ raise ValueError('Non-None value (%r) with "is" comparison_operator. Not sure what to do.' % (value, ))
self.value = value
self.comparison_operator = comparison_operator
self.group = group
diff --git a/product/ZSQLCatalog/SQLExpression.py b/product/ZSQLCatalog/SQLExpression.py
index a74f365c0e79485a23b194c88d013b45caadb632..1797903b6e5effe34af35cef1a98efc0aa4437e5 100644
--- a/product/ZSQLCatalog/SQLExpression.py
+++ b/product/ZSQLCatalog/SQLExpression.py
@@ -125,7 +125,7 @@ class SQLExpression(object):
if len(limit) < 3:
self.limit = limit
else:
- raise ValueError, 'Unrecognized "limit" value: %r' % (limit, )
+ raise ValueError('Unrecognized "limit" value: %r' % (limit, ))
else:
self.limit = (limit, )
if from_expression is not None:
@@ -188,7 +188,7 @@ class SQLExpression(object):
sql_expression,
sql_expression.query,
', '.join('%r (%r)' % (x, x.query) for x in self.sql_expression_list))
- raise ValueError, message
+ raise ValueError(message)
result[alias] = table_name
return result
@@ -211,7 +211,7 @@ class SQLExpression(object):
sql_expression,
sql_expression.query,
', '.join('%r (%r)' % (x, x.query) for x in self.sql_expression_list))
- raise ValueError, message
+ raise ValueError(message)
return result
def getOrderByList(self):
@@ -251,7 +251,7 @@ class SQLExpression(object):
if delay_error:
order_by_dict[key] = MergeConflict(message)
else:
- raise MergeConflictError, message
+ raise MergeConflictError(message)
result_dict.update(order_by_dict)
return result_dict
@@ -317,7 +317,7 @@ class SQLExpression(object):
sql_expression,
sql_expression.query,
', '.join('%r (%r)' % (x, x.query) for x in self.sql_expression_list))
- raise ValueError, message
+ raise ValueError(message)
return result
def getLimitExpression(self):
diff --git a/product/ZSQLCatalog/SearchKey/DateTimeKey.py b/product/ZSQLCatalog/SearchKey/DateTimeKey.py
index 247cbf0bcd8b033e48504a3f69d7e3c456e2489e..09172aa80816349cc35a13fa8e06d600f0d05036 100644
--- a/product/ZSQLCatalog/SearchKey/DateTimeKey.py
+++ b/product/ZSQLCatalog/SearchKey/DateTimeKey.py
@@ -90,7 +90,7 @@ def castDate(value, change_timezone=True):
else:
raise
else:
- raise TypeError, 'Unknown date type: %r' % (value)
+ raise TypeError('Unknown date type: %r' % (value))
if change_timezone:
return value.toZone('UTC')
else:
@@ -139,9 +139,9 @@ def getPeriodBoundaries(value):
if isinstance(value, basestring):
delimiter_count = countDelimiters(value)
elif isinstance(value, DateTime):
- raise TypeError, 'Impossible to guess a precision from a DateTime type.'
+ raise TypeError('Impossible to guess a precision from a DateTime type.')
else:
- raise TypeError, 'Unknown date type: %r' % (value)
+ raise TypeError('Unknown date type: %r' % (value))
delta = delta_list[delimiter_count]
if callable(delta):
delta = delta(first_date)
diff --git a/product/ZSQLCatalog/SearchKey/SearchKey.py b/product/ZSQLCatalog/SearchKey/SearchKey.py
index 5a0fcf66ef93b4114eb76b79be1cf0298bd2515b..52e485f745b6670edcadc3c9a9eb1c78c6019991 100644
--- a/product/ZSQLCatalog/SearchKey/SearchKey.py
+++ b/product/ZSQLCatalog/SearchKey/SearchKey.py
@@ -243,24 +243,24 @@ class SearchKey(object):
comparison_operator = single_operator_dict[value_range]
elif value_range in dual_operator_dict:
if not isinstance(actual_value, (tuple, list)):
- raise TypeError, 'Operator %r requires value to be a '\
+ raise TypeError('Operator %r requires value to be a '\
'tuple/list. (%r)' % (value_range,
- search_value)
+ search_value))
if len(actual_value) != 2:
- raise TypeError, 'Operator %r requires value to have a length '\
+ raise TypeError('Operator %r requires value to have a length '\
'of 2. len(%r) = %i (%r)' % (value_range,
- actual_value, len(actual_value), search_value)
+ actual_value, len(actual_value), search_value))
comparison_operator = dual_operator_dict[value_range]
logical_operator = 'and'
else:
- raise ValueError, 'Unknown "range" value in %r' % (search_value, )
+ raise ValueError('Unknown "range" value in %r' % (search_value, ))
if value_operator is not None:
if not isinstance(value_operator, basestring):
- raise TypeError, 'Operator must be of a string type. Got a %r' % \
- (type(value_operator), )
+ raise TypeError('Operator must be of a string type. Got a %r' % \
+ (type(value_operator), ))
value_operator = value_operator.lower()
if not isinstance(actual_value, (tuple, list)):
- raise TypeError, 'When specifying an operator, query must be a list.'
+ raise TypeError('When specifying an operator, query must be a list.')
if value_operator == 'in':
comparison_operator = '='
logical_operator = 'or'
diff --git a/product/ZSQLCatalog/SearchText/SearchTextParser.py b/product/ZSQLCatalog/SearchText/SearchTextParser.py
index a20ff11963c1596ee4ffb73fd880d3a962988fcb..978e5ce9325c9bd48be60afc3c3a8ed6ce8267a6 100755
--- a/product/ZSQLCatalog/SearchText/SearchTextParser.py
+++ b/product/ZSQLCatalog/SearchText/SearchTextParser.py
@@ -51,7 +51,7 @@ class ParserPool(object):
parser_registry = self.parser_registry
name = '.'.join((parser.__module__, parser.__name__))
if name in parser_registry:
- raise ValueError, 'Duplicate parser for name %r' % (name, )
+ raise ValueError('Duplicate parser for name %r' % (name, ))
parser_registry[name] = parser
return name
@@ -306,7 +306,7 @@ if __name__ == '__main__':
for input, expected in check_list:
try:
result = parse(input)
- except ParserOrLexerError, message:
+ except ParserOrLexerError as message:
print "ERROR when checking %r" % (input, )
print " crashed with: %s" % (message, )
print " instead of producing %r" % (expected, )
@@ -328,7 +328,7 @@ if __name__ == '__main__':
try:
detector_result = parser_pool.get(DETECTOR_ID)(input,
isColumn)
- except ParserOrLexerError, message:
+ except ParserOrLexerError as message:
print ' Detector raise: %r' % (message, )
detector_result = False
else:
@@ -348,7 +348,7 @@ if __name__ == '__main__':
print ' %r' % (parse(input, debug=2), )
else:
print ' %r' % (input, )
- except ParserOrLexerError, message:
+ except ParserOrLexerError as message:
print message
print
diff --git a/product/ZSQLCatalog/SearchText/lexer.py b/product/ZSQLCatalog/SearchText/lexer.py
index 01b3b88fe2418de995c3be66261dbc60870f28e6..fbae816a85026ca3335a75ac564316346b301948 100644
--- a/product/ZSQLCatalog/SearchText/lexer.py
+++ b/product/ZSQLCatalog/SearchText/lexer.py
@@ -61,10 +61,10 @@ class lexer(object):
LOG('lexer', 0, line)
def t_error(self, t):
- raise LexerError, 'ERROR: Invalid character %r' % (t.value[0], )
+ raise LexerError('ERROR: Invalid character %r' % (t.value[0], ))
def p_error(self, p):
- raise ParserError, 'Syntax error in input: %r' % (p, )
+ raise ParserError('Syntax error in input: %r' % (p, ))
def input(self, string):
self.lexer.input(string)
diff --git a/product/ZSQLCatalog/ZSQLCatalog.py b/product/ZSQLCatalog/ZSQLCatalog.py
index 564138b24be1b95645babd21ef4955253f39e3c8..64c23fdf1eeeda75c90e59bb0045901e39f195b2 100644
--- a/product/ZSQLCatalog/ZSQLCatalog.py
+++ b/product/ZSQLCatalog/ZSQLCatalog.py
@@ -259,7 +259,7 @@ class ZCatalog(Folder, Persistent, Implicit):
self.destination_sql_catalog_id = destination_sql_catalog_id
self.archive_path = archive_path
else:
- raise CatalogError, 'unknown hot reindexing state %s' % state
+ raise CatalogError('unknown hot reindexing state %s' % state)
def _finishHotReindexing(self, source_sql_catalog_id,
destination_sql_catalog_id, skin_selection_dict,
@@ -293,8 +293,8 @@ class ZCatalog(Folder, Persistent, Implicit):
ERP5Site_reindexAll.
"""
if self.getHotReindexingState() == HOT_REINDEXING_FINISHED_STATE:
- raise Exception, 'cancelHotReindexing called while no Hot Reindexing '\
- 'was runing. Nothing done.'
+ raise Exception('cancelHotReindexing called while no Hot Reindexing '\
+ 'was runing. Nothing done.')
# Remove hot reindexing state
self._setHotReindexingState(HOT_REINDEXING_FINISHED_STATE)
portal_activities = getToolByName(self, 'portal_activities')
@@ -323,9 +323,9 @@ class ZCatalog(Folder, Persistent, Implicit):
transaction.
"""
if self.getHotReindexingState() != HOT_REINDEXING_DOUBLE_INDEXING_STATE:
- raise Exception, 'playBackRecordedObjectList was called while '\
+ raise Exception('playBackRecordedObjectList was called while '\
'hot_reindexing_state was not "%s". Playback aborted.' \
- % (HOT_REINDEXING_DOUBLE_INDEXING_STATE, )
+ % (HOT_REINDEXING_DOUBLE_INDEXING_STATE, ))
catalog_object = self.getSQLCatalog(sql_catalog_id)
result = catalog_object.readRecordedObjectList(catalog=catalog)
if len(result):
@@ -337,7 +337,7 @@ class ZCatalog(Folder, Persistent, Implicit):
if obj is not None:
obj.reindexObject(sql_catalog_id=sql_catalog_id)
else:
- raise ValueError, '%s is not a valid value for "catalog".' % (catalog, )
+ raise ValueError('%s is not a valid value for "catalog".' % (catalog, ))
catalog_object.deleteRecordedObjectList(uid_list=[o.uid for o in result])
# Re-schedule the same action in case there are remaining rows in the
# table. This can happen if the database connector limits the number
@@ -428,13 +428,13 @@ class ZCatalog(Folder, Persistent, Implicit):
"""
# Hot reindexing can only be runing once at a time on a system.
if self.hot_reindexing_state is not None:
- raise CatalogError, 'hot reindexing process is already running %s -%s' %(self, self.hot_reindexing_state)
+ raise CatalogError('hot reindexing process is already running %s -%s' %(self, self.hot_reindexing_state))
if source_sql_catalog_id == destination_sql_catalog_id:
- raise CatalogError, 'Hot reindexing cannot be done with the same '\
+ raise CatalogError('Hot reindexing cannot be done with the same '\
'catalog as both source and destination. What'\
' you want to do is a "clear catalog" and an '\
- '"ERP5Site_reindexAll".'
+ '"ERP5Site_reindexAll".')
if source_sql_catalog_id != self.getDefaultSqlCatalogId():
LOG('ZSQLCatalog', 0, 'Warning : Hot reindexing is started with a '\
@@ -832,7 +832,7 @@ class ZCatalog(Folder, Persistent, Implicit):
def uncatalog_object(self, uid=None,path=None, sql_catalog_id=None):
""" wrapper around catalog """
if uid is None:
- raise TypeError, "sorry uncatalog_object supports only uid"
+ raise TypeError("sorry uncatalog_object supports only uid")
default_catalog = self.getSQLCatalog()
if sql_catalog_id is None:
@@ -1153,7 +1153,7 @@ class ZCatalog(Folder, Persistent, Implicit):
try: add_result=result.append
except AttributeError:
- raise AttributeError, `result`
+ raise AttributeError(`result`)
for id, ob in items:
if pre: p="%s/%s" % (pre, id)
diff --git a/product/ZSQLCatalog/tests/testSQLCatalog.py b/product/ZSQLCatalog/tests/testSQLCatalog.py
index 553274ec67ea3372e9bdd09114814004e9924026..51c369c2ff13433ce446fd5cbe1682fa53946ff2 100644
--- a/product/ZSQLCatalog/tests/testSQLCatalog.py
+++ b/product/ZSQLCatalog/tests/testSQLCatalog.py
@@ -102,7 +102,7 @@ class ReferenceQuery:
value = MatchList([value])
self.value = value
elif len(kw) > 1:
- raise ValueError, 'kw must not have more than one item: %r' % (kw, )
+ raise ValueError('kw must not have more than one item: %r' % (kw, ))
def __eq__(self, other):
if isinstance(other, SimpleQuery):
@@ -132,7 +132,7 @@ class ReferenceQuery:
elif isinstance(other, Query):
return self == other.wrapped_query
else:
- raise TypeError, 'Compared value is not a (known) Query instance: (%s) %r' % (other.__class__.__name__, other)
+ raise TypeError('Compared value is not a (known) Query instance: (%s) %r' % (other.__class__.__name__, other))
def __repr__(self):
if self.args:
diff --git a/product/Zelenium/generator.py b/product/Zelenium/generator.py
index aff859ba4076fe08aec663030bb3a70d9b6439ea..4ee52b598915f2de5bd57eb60c650f276bc97dc1 100644
--- a/product/Zelenium/generator.py
+++ b/product/Zelenium/generator.py
@@ -181,7 +181,7 @@ class ScenarioGenerator:
, 'test-case-title='
]
)
- except getopt.GetoptError, msg:
+ except getopt.GetoptError as msg:
self.printUsage( msg=msg)
for o, v in opts:
diff --git a/product/Zelenium/tests/test_zuite.py b/product/Zelenium/tests/test_zuite.py
index 8365a2a85a773be9b515a319c326cb8ad33578e3..4983f8e77baad9f40bbef4de541997d930e3ef14 100644
--- a/product/Zelenium/tests/test_zuite.py
+++ b/product/Zelenium/tests/test_zuite.py
@@ -131,11 +131,11 @@ class ZuiteTests( unittest.TestCase ):
for name in names:
if name not in contents:
- raise AssertionError, 'Extra name in archive: %s' % name
+ raise AssertionError('Extra name in archive: %s' % name)
for name in contents:
if name not in names:
- raise AssertionError, 'Missing name in archive: %s' % name
+ raise AssertionError('Missing name in archive: %s' % name)
def _verifyManifest( self, bits, name, contents ):
diff --git a/product/Zelenium/zuite.py b/product/Zelenium/zuite.py
index c00f71927674788d86895170c6f735d1879ece91..f46ad5f542cedb881d2dc75ad75882cd2a683238 100644
--- a/product/Zelenium/zuite.py
+++ b/product/Zelenium/zuite.py
@@ -201,7 +201,7 @@ class Zuite( OrderedFolder ):
if value is not _MARKER:
return value
- raise KeyError, key
+ raise KeyError(key)
security.declareProtected( View, 'listTestCases' )
@@ -678,7 +678,7 @@ class ZuiteResults( Folder ):
if default is not _MARKER:
return default
- raise KeyError, key
+ raise KeyError(key)
InitializeClass( ZuiteResults )
@@ -718,7 +718,7 @@ class _FilesystemProxy( Folder ):
if default is not _MARKER:
return default
- raise KeyError, key
+ raise KeyError(key)
security.declareProtected( View, 'listTestCases' )
def listTestCases( self, prefix=() ):