Skip to content

Commit

Permalink
Merge pull request #198 from DimitriPapadopoulos/ruff
Browse files Browse the repository at this point in the history
Apply ruff rules to Python scripts
  • Loading branch information
sbesson authored Jan 22, 2025
2 parents 7543f63 + 2db8c35 commit a3c7457
Show file tree
Hide file tree
Showing 12 changed files with 108 additions and 174 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python2

# #%L
# OME Data Model transforms
Expand Down
106 changes: 48 additions & 58 deletions xsd-fu/python/generateDS/generateDS.py

Large diffs are not rendered by default.

16 changes: 7 additions & 9 deletions xsd-fu/python/generateDS/process_includes.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
-h, --help Display this help message.
-f, --force Force. If outfile exists, overwrite without asking.
-s, --search Search path for schemas. Colon separated list of directories where schemas may be found.
Examples:
python process_includes.py infile.xsd
python process_includes.py infile.xsd outfile.xsd
Expand Down Expand Up @@ -106,13 +106,13 @@ def process_path(root, idx, path):

def process_include_tree(root):
global DIRPATH

idx = 0
children = root.getchildren()
while idx < len(children):
child = children[idx]
tag = child.tag
if type(tag) == type(""):
if type(tag) == str:
tag = NAMESPACE_PAT.sub("", tag)
else:
tag = None
Expand All @@ -130,17 +130,17 @@ def process_include_tree(root):
break
else:
msg = "Can't find include file %s. Aborting." % (path, )
raise IOError(msg)
raise OSError(msg)
elif tag == 'import' and 'schemaLocation' in child.attrib:
root.remove(child)
locn = child.attrib['schemaLocation']
if locn.startswith('ftp:') or locn.startswith('http:'):
if locn.startswith(('ftp:', 'http:')):
try:
path, msg = urllib.request.urlretrieve(locn)
idx = process_path(root, idx, path)
except:
msg = "Can't retrieve import file %s. Aborting." % (locn, )
raise IOError(msg)
raise OSError(msg)
else:
if os.path.exists(locn):
idx = process_path(root, idx, locn)
Expand All @@ -152,7 +152,7 @@ def process_include_tree(root):
break
else:
msg = "Can't find import file %s. Aborting." % (locn, )
raise IOError(msg)
raise OSError(msg)
else:
process_include_tree(child)
idx += 1
Expand Down Expand Up @@ -211,5 +211,3 @@ def main():
if __name__ == '__main__':
#import pdb; pdb.set_trace()
main()


3 changes: 1 addition & 2 deletions xsd-fu/python/ome/modeltools/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,10 @@
import logging

from ome.modeltools import config
from ome.modeltools import language
from ome.modeltools.exceptions import ModelProcessingError


class OMEModelEntity(object):
class OMEModelEntity:
"""
An abstract root class for properties and model objects containing
common type resolution and text processing functionality.
Expand Down
1 change: 0 additions & 1 deletion xsd-fu/python/ome/modeltools/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,3 @@ class ModelProcessingError(Exception):
"""
Raised when there is an error during model processing.
"""
pass
56 changes: 20 additions & 36 deletions xsd-fu/python/ome/modeltools/language.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
TYPE_SOURCE = "source"


class Language(object):
class Language:
"""
Base class for output language.
Updates the type maps with the model namespace.
Expand Down Expand Up @@ -91,11 +91,11 @@ def __init__(self, namespace, templatepath):
'Text': 'Text',
namespace + 'dateTime': 'Timestamp'
}

# A global type mapping from XSD Schema substitution groups to language abstract classes
self.abstract_type_map = dict()
# A global type mapping from XSD Schema abstract classes to their equivalent substitution group
self.substitutionGroup_map = dict()
self.substitutionGroup_map = dict()

# A global type mapping from XSD Schema elements to language model
# object classes. This will cause source code generation to be
Expand All @@ -109,8 +109,8 @@ def __init__(self, namespace, templatepath):
'UniversallyUniqueIdentifier': self.getDefaultModelBaseClass(),
'base64Binary': self.getDefaultModelBaseClass()
}
# A global set XSD Schema types use as base classes which are primitive

# A global set XSD Schema types use as base classes which are primitive
self.primitive_base_types = set([
"base64Binary"])

Expand Down Expand Up @@ -150,10 +150,10 @@ def templatepath(self, template):

def getConverterDir(self):
return self.converter_dir

def getConverterName(self):
return self.converter_name

def generatedFilename(self, name, type):
gen_name = None
if type == TYPE_SOURCE and self.source_suffix is not None:
Expand All @@ -165,9 +165,7 @@ def generatedFilename(self, name, type):
return gen_name

def hasBaseType(self, type):
if type in self.base_type_map:
return True
return False
return type in self.base_type_map

def baseType(self, type):
try:
Expand All @@ -176,57 +174,43 @@ def baseType(self, type):
return None

def hasFundamentalType(self, type):
if type in self.fundamental_types:
return True
return False
return type in self.fundamental_types

def hasPrimitiveType(self, type):
if (type in list(self.primitive_type_map.values()) or
type in self.primitive_types):
return True
return False
return type in list(self.primitive_type_map.values()) or type in self.primitive_types

def primitiveType(self, type):
try:
return self.primitive_type_map[type]
except KeyError:
return None

def hasAbstractType(self, type):
if (type in self.abstract_type_map):
return True
return False
return type in self.abstract_type_map

def abstractType(self, type):
try:
return self.abstract_type_map[type]
except KeyError:
return None

def hasSubstitutionGroup(self, type):
if (type in self.substitutionGroup_map):
return True
return False
return type in self.substitutionGroup_map

def substitutionGroup(self, type):
try:
return self.substitutionGroup_map[type]
except KeyError:
return None

def getSubstitutionTypes(self):
return list(self.substitutionGroup_map.keys())

def isPrimitiveBase(self, type):
if type in self.primitive_base_types:
return True
else:
return False
return type in self.primitive_base_types

def hasType(self, type):
if type in self.type_map:
return True
return False
return type in self.type_map

def type(self, type):
try:
Expand Down Expand Up @@ -258,7 +242,7 @@ def index_argname(self, signature, dummy=False):

class Java(Language):
def __init__(self, namespace, templatepath):
super(Java, self).__init__(namespace, templatepath)
super().__init__(namespace, templatepath)

self.package_separator = '.'

Expand Down Expand Up @@ -333,7 +317,7 @@ def typeToDefault(self, unitType):
def index_signature(self, name, max_occurs, level, dummy=False):
"""Makes a Java method signature dictionary from an index name."""

sig = super(Java, self).index_signature(name, max_occurs, level, dummy)
sig = super().index_signature(name, max_occurs, level, dummy)
sig['argtype'] = 'int'

return sig
Expand Down
12 changes: 6 additions & 6 deletions xsd-fu/python/ome/modeltools/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from ome.modeltools import config


class ReferenceDelegate(object):
class ReferenceDelegate:
"""
A "virtual" property delegate to be used with "reference"
OMEModelProperty instances. This delegate conforms loosely to the same
Expand Down Expand Up @@ -68,7 +68,7 @@ def getMinOccurs(self):

def getType(self):
return self.dataType

def getData_type(self):
return self.dataType

Expand All @@ -79,7 +79,7 @@ def isComplex(self):
return True


class OMEModel(object):
class OMEModel:
def __init__(self, opts):
self.opts = opts
self.elementNameObjectMap = dict()
Expand Down Expand Up @@ -203,7 +203,7 @@ def processTree(self, elements, parent=None):
if parent is not None:
element = self.substitutionElement_map[element.getName()]
if parent is None:
continue
continue
logging.info("Processing element: %s %d/%d"
% (element, i + 1, length))
self.processLeaf(element, parent)
Expand Down Expand Up @@ -323,13 +323,13 @@ def populateSubstitutionGroups(self, elements):
Creates a mapping between substitution group elements and their type elements
"""
length = len(elements)
for i, element in enumerate(elements):
for element in elements:
if 'substitutionGroup' in element.getAttrs():
substitutionGroup = element.getAttrs()['substitutionGroup']
base = element.getBase()
self.opts.lang.abstract_type_map[substitutionGroup] = base
self.opts.lang.substitutionGroup_map[base] = substitutionGroup
for i, element in enumerate(elements):
for element in elements:
if self.opts.lang.hasSubstitutionGroup(element.getName()):
substitutionGroupName = self.opts.lang.substitutionGroup(element.getName())
self.substitutionElement_map[substitutionGroupName] = element
Expand Down
18 changes: 4 additions & 14 deletions xsd-fu/python/ome/modeltools/object.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@

from collections import OrderedDict
import logging
import re

from xml.etree import ElementTree

Expand Down Expand Up @@ -97,7 +96,7 @@ def addBaseAttribute(self, delegate, namespace):
prop.isBackReference = False
prop.isAttribute = True
self.properties[delegate.name] = prop

def addAttribute(self, attribute):
"""
Adds an OME XML Schema attribute to the object's data model.
Expand Down Expand Up @@ -132,19 +131,13 @@ def _get_isReference(self):
if self.base == "Reference":
return True
typeObject = self.model.getObjectByName(self.type)
if (typeObject is not None and typeObject.name != self.name and
typeObject.isReference):
return True
return False
return typeObject is not None and typeObject.name != self.name and typeObject.isReference
isReference = property(
_get_isReference,
doc="""Whether or not the model object is a reference.""")

def _get_isAnnotated(self):
for v in self.properties.values():
if v.name == "AnnotationRef":
return True
return False
return any(v.name == 'AnnotationRef' for v in self.properties.values())
isAnnotated = property(
_get_isAnnotated,
doc="""Whether or not the model object is annotated.""")
Expand All @@ -159,10 +152,7 @@ def _get_isNamed(self):
doc="""Whether or not the model object is named.""")

def _get_isDescribed(self):
for v in self.properties.values():
if v.name == "Description":
return True
return False
return any(v.name == 'Description' for v in self.properties.values())
isDescribed = property(
_get_isDescribed,
doc="""Whether or not the model object is described.""")
Expand Down
22 changes: 6 additions & 16 deletions xsd-fu/python/ome/modeltools/property.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,7 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from collections import OrderedDict
import logging
import re

from xml.etree import ElementTree

Expand Down Expand Up @@ -274,34 +272,26 @@ def _get_isAnnotation(self):
doc="""Whether or not the property is an Annotation.""")

def _get_isPrimitive(self):
if self.model.opts.lang.hasPrimitiveType(self.langType):
return True
return False
return self.model.opts.lang.hasPrimitiveType(self.langType)
isPrimitive = property(
_get_isPrimitive,
doc="""Whether or not the property's language type is a primitive.""")

def _get_isEnumeration(self):
v = self.delegate.getValues()
if v is not None and len(v) > 0:
return True
return False
return v is not None and len(v) > 0
isEnumeration = property(
_get_isEnumeration,
doc="""Whether or not the property is an enumeration.""")

def _get_isUnitsEnumeration(self):
if self.langType.startswith("Units"):
return True
return False
return self.langType.startswith('Units')
isUnitsEnumeration = property(
_get_isUnitsEnumeration,
doc="""Whether or not the property is a units enumeration.""")

def _get_hasUnitsCompanion(self):
if self.name+"Unit" in self.parent.properties:
return True
return False
return self.name + 'Unit' in self.parent.properties
hasUnitsCompanion = property(
_get_hasUnitsCompanion,
doc="""Whether or not the property has a units companion.""")
Expand Down Expand Up @@ -395,7 +385,7 @@ def _get_isReference(self):
def _get_concreteClasses(self):
returnList = []
if self.model.opts.lang.hasSubstitutionGroup(self.name):
for o in sorted(list(self.model.objects.values()), key=lambda x: x.name):
for o in sorted(self.model.objects.values(), key=lambda x: x.name):
if o.parentName == self.name:
returnList.append(o.name)
return returnList
Expand Down Expand Up @@ -586,7 +576,7 @@ def _get_isAbstract(self):
isAbstract = property(
_get_isAbstract,
doc="""Is the property abstract.""")

def _get_isAbstractSubstitution(self):
return self.model.opts.lang.hasSubstitutionGroup(self.name)
isAbstractSubstitution = property(
Expand Down
Loading

0 comments on commit a3c7457

Please sign in to comment.