[PATCH 1 of 9 yams V2] autopep8 and manual modifications to please pep8

Laurent Peuch cortex at worlddomination.be
Wed Jan 15 10:58:24 CET 2020


# HG changeset patch
# User Laurent Peuch <cortex at worlddomination.be>
# Date 1578577998 -3600
#      Thu Jan 09 14:53:18 2020 +0100
# Node ID 097005e98040682c83769e741142121654987b5d
# Parent  9578376f98bd95d3419bdead85ece7d7abfad271
# Available At https://hg.logilab.org/users/lpeuch/yams
#              hg pull https://hg.logilab.org/users/lpeuch/yams -r 097005e98040
autopep8 and manual modifications to please pep8

diff --git a/yams/_exceptions.py b/yams/_exceptions.py
--- a/yams/_exceptions.py
+++ b/yams/_exceptions.py
@@ -19,8 +19,6 @@
 
 __docformat__ = "restructuredtext en"
 
-import sys
-
 
 class SchemaError(Exception):
     """base class for schema exceptions"""
@@ -133,8 +131,7 @@ class ValidationError(SchemaError):
         for key, msg in self.errors.items():
             msg = _(msg)
             if key is not None:
-                msg = msg.replace('%(KEY-', '%('+key+'-')
+                msg = msg.replace('%(KEY-', '%(' + key + '-')
             if self.msgargs:
                 msg = msg % self.msgargs
             yield key, msg
-
diff --git a/yams/buildobjs.py b/yams/buildobjs.py
--- a/yams/buildobjs.py
+++ b/yams/buildobjs.py
@@ -31,8 +31,10 @@ from yams.constraints import (SizeConstr
                               StaticVocabularyConstraint, FORMAT_CONSTRAINT)
 from yams.schema import RelationDefinitionSchema
 
-PACKAGE = '<builtin>' # will be modified by the yams'reader when schema is
-                      # beeing read
+# will be modified by the yams'reader when schema is
+# beeing read
+PACKAGE = '<builtin>'
+
 
 __all__ = ('EntityType', 'RelationType', 'RelationDefinition',
            'SubjectRelation', 'ObjectRelation',
@@ -44,6 +46,8 @@ ETYPE_PROPERTIES = ('description', '__pe
 RTYPE_PROPERTIES = ('symmetric', 'inlined', 'fulltext_container')
 # RelationDefinition properties have to be computed dynamically since new ones
 # may be added at runtime
+
+
 def _RDEF_PROPERTIES():
     base = RelationDefinitionSchema.ALL_PROPERTIES()
     # infered is an internal property and should not be specified explicitly
@@ -55,15 +59,19 @@ def _RDEF_PROPERTIES():
     return tuple(base)
 # regroup all rtype/rdef properties as they may be defined one on each other in
 # some cases
+
+
 def _REL_PROPERTIES():
     return RTYPE_PROPERTIES + _RDEF_PROPERTIES()
 
+
 # pre 0.37 backward compat
-RDEF_PROPERTIES = () # stuff added here is also added to underlying dict, nevermind
+RDEF_PROPERTIES = ()  # stuff added here is also added to underlying dict, nevermind
 
 
 CREATION_RANK = 0
 
+
 def _add_constraint(kwargs, constraint):
     """Add constraint to param kwargs."""
     constraints = kwargs.setdefault('constraints', [])
@@ -73,6 +81,7 @@ def _add_constraint(kwargs, constraint):
             return
     constraints.append(constraint)
 
+
 def _add_relation(relations, rdef, name=None, insertidx=None):
     """Add relation (param rdef) to list of relations (param relations)."""
     if name is not None:
@@ -83,24 +92,26 @@ def _add_relation(relations, rdef, name=
     if getattr(rdef, 'metadata', {}):
         for meta_name, value in rdef.metadata.items():
             assert meta_name in KNOWN_METAATTRIBUTES
-            insertidx += 1 # insert meta after main
+            insertidx += 1  # insert meta after main
             meta_rel_name = '_'.join(((name or rdef.name), meta_name))
             _add_relation(relations, value, meta_rel_name, insertidx)
 
+
 def _check_kwargs(kwargs, attributes):
     """Check that all keys of kwargs are actual attributes."""
     for key in kwargs:
-        if not key in attributes:
+        if key not in attributes:
             raise BadSchemaDefinition('no such property %r in %r'
                                       % (key, attributes))
 
+
 def _copy_attributes(fromobj, toobj, attributes):
     for attr in attributes:
         value = getattr(fromobj, attr, MARKER)
         if value is MARKER:
             continue
         ovalue = getattr(toobj, attr, MARKER)
-        if not ovalue is MARKER and value != ovalue:
+        if ovalue is not MARKER and value != ovalue:
             rname = getattr(toobj, 'name', None) or toobj.__name__
             raise BadSchemaDefinition(
                 'conflicting values %r/%r for property %s of relation %r'
@@ -220,6 +231,7 @@ class AbstractTypedAttribute(SubjectRela
 
     subclasses must provide a <etype> attribute to be instantiable
     """
+
     def __init__(self, metadata=None, **kwargs):
         # Store metadata
         if metadata is None:
@@ -253,7 +265,7 @@ class AbstractTypedAttribute(SubjectRela
         # Main attribute are marked as created before it's metadata.
         # order in meta data is preserved.
         if self.metadata:
-            meta = sorted(metadata.values(), key= lambda x: x.creation_rank)
+            meta = sorted(metadata.values(), key=lambda x: x.creation_rank)
             if meta[0].creation_rank < self.creation_rank:
                 m_iter = iter(meta)
                 previous = self
@@ -266,9 +278,9 @@ class AbstractTypedAttribute(SubjectRela
     def set_vocabulary(self, vocabulary, kwargs=None):
         if kwargs is None:
             kwargs = self.__dict__
-        #constraints = kwargs.setdefault('constraints', [])
+        # constraints = kwargs.setdefault('constraints', [])
         _add_constraint(kwargs, StaticVocabularyConstraint(vocabulary))
-        if self.__class__.__name__ == 'String': # XXX
+        if self.__class__.__name__ == 'String':  # XXX
             maxsize = max(len(x) for x in vocabulary)
             _add_constraint(kwargs, SizeConstraint(max=maxsize))
 
@@ -293,7 +305,7 @@ def make_type(etype):
     make_type.
     """
     assert etype in BASE_TYPES
-    return type(etype, (AbstractTypedAttribute,), {'etype' : etype})
+    return type(etype, (AbstractTypedAttribute,), {'etype': etype})
 
 
 # build a specific class for each base type
@@ -336,7 +348,7 @@ def RichString(default_format='text/plai
         format_args['constraints'] = [FORMAT_CONSTRAINT]
     else:
         format_args['constraints'] = format_constraints
-    meta = {'format':String(internationalizable=True, **format_args)}
+    meta = {'format': String(internationalizable=True, **format_args)}
     return String(metadata=meta, **kwargs)
 
 
@@ -347,8 +359,9 @@ class metadefinition(autopackage):
     subclasses.
     """
     stacklevel = 3
+
     def __new__(mcs, name, bases, classdict):
-        ### Move (any) relation from the class dict to __relations__ attribute
+        # Move (any) relation from the class dict to __relations__ attribute
         rels = classdict.setdefault('__relations__', [])
         relations = dict((rdef.name, rdef) for rdef in rels)
         for rname, rdef in list(classdict.items()):
@@ -357,21 +370,21 @@ class metadefinition(autopackage):
                 # to avoid conflicts with instance's potential attributes
                 del classdict[rname]
                 relations[rname] = rdef
-        ### handle logical inheritance
+        # handle logical inheritance
         if '__specializes_schema__' in classdict:
             specialized = bases[0]
             classdict['__specializes__'] = specialized.__name__
             if '__specialized_by__' not in specialized.__dict__:
                 specialized.__specialized_by__ = []
             specialized.__specialized_by__.append(name)
-        ### Initialize processed class
+        # Initialize processed class
         defclass = super(metadefinition, mcs).__new__(mcs, name, bases, classdict)
         for rname, rdef in relations.items():
             _add_relation(defclass.__relations__, rdef, rname)
-        ### take base classes'relations into account
+        # take base classes'relations into account
         for base in bases:
             for rdef in getattr(base, '__relations__', ()):
-                if not rdef.name in relations or not relations[rdef.name].override:
+                if rdef.name not in relations or not relations[rdef.name].override:
                     if isinstance(rdef, RelationDefinition):
                         rdef = copy(rdef)
                         if rdef.subject == base.__name__:
@@ -381,35 +394,35 @@ class metadefinition(autopackage):
                     rels.append(rdef)
                 else:
                     relations[rdef.name].creation_rank = rdef.creation_rank
-        ### sort relations by creation rank
+        # sort relations by creation rank
         defclass.__relations__ = sorted(rels, key=lambda r: r.creation_rank)
         return defclass
 
 
 class EntityType(Definition, metaclass=metadefinition):
-    #::FIXME reader magic forbids to define a docstring...
-    #: an entity has attributes and can be linked to other entities by
-    #: relations. Both entity attributes and relationships are defined by
-    #: class attributes.
-    #:
-    #: kwargs keys must have values in ETYPE_PROPERTIES
-    #:
-    #: Example:
-    #:
-    #: >>> class Project(EntityType):
-    #: ...     name = String()
-    #: >>>
-    #:
-    #: After instanciation, EntityType can we altered with dedicated class methods:
-    #:
-    #: .. currentmodule:: yams.buildobjs
-    #:
-    #:  .. automethod:: EntityType.extend
-    #:  .. automethod:: EntityType.add_relation
-    #:  .. automethod:: EntityType.insert_relation_after
-    #:  .. automethod:: EntityType.remove_relation
-    #:  .. automethod:: EntityType.get_relation
-    #:  .. automethod:: EntityType.get_relations
+    # :FIXME reader magic forbids to define a docstring...
+    #  an entity has attributes and can be linked to other entities by
+    #  relations. Both entity attributes and relationships are defined by
+    #  class attributes.
+    #
+    #  kwargs keys must have values in ETYPE_PROPERTIES
+    #
+    #  Example:
+    #
+    #  >>> class Project(EntityType):
+    #  ...     name = String()
+    #  >>>
+    #
+    #  After instanciation, EntityType can we altered with dedicated class methods:
+    #
+    #  .. currentmodule:: yams.buildobjs
+    #
+    #   .. automethod:: EntityType.extend
+    #   .. automethod:: EntityType.add_relation
+    #   .. automethod:: EntityType.insert_relation_after
+    #   .. automethod:: EntityType.remove_relation
+    #   .. automethod:: EntityType.get_relation
+    #   .. automethod:: EntityType.get_relations
 
     __permissions__ = DEFAULT_ETYPEPERMS
 
@@ -436,7 +449,7 @@ class EntityType(Definition, metaclass=m
         assert name not in defined, \
             "type '%s' was already defined here %s, new definition here %s" % \
             (name, defined[name].__module__, cls)
-        cls._defined = defined # XXX may be used later (eg .add_relation())
+        cls._defined = defined  # XXX may be used later (eg .add_relation())
         defined[name] = cls
         for relation in cls.__relations__:
             cls._ensure_relation_type(relation)
@@ -449,7 +462,7 @@ class EntityType(Definition, metaclass=m
         (XXX raise excep instead ?)"""
         rtype = RelationType(relation.name)
         _copy_attributes(relation, rtype, RTYPE_PROPERTIES)
-        #assert hasattr(cls, '_defined'), "Type definition for %s not yet expanded. you can't register new type through it" % cls
+        # assert hasattr(cls, '_defined'), "Type definition for %s not yet expanded. you can't register new type through it" % cls
         if hasattr(cls, '_defined'):
             defined = cls._defined
             if relation.name in defined:
@@ -503,13 +516,13 @@ class EntityType(Definition, metaclass=m
             rdef.name = name
         if cls._ensure_relation_type(rdef):
             _add_relation(cls.__relations__, rdef, name)
-            if getattr(rdef, 'metadata', {}) and not rdef in cls._defined:
+            if getattr(rdef, 'metadata', {}) and rdef not in cls._defined:
                 for meta_name in rdef.metadata:
                     format_attr_name = '_'.join(((name or rdef.name), meta_name))
                     rdef = next(cls.get_relations(format_attr_name))
                     cls._ensure_relation_type(rdef)
         else:
-           _add_relation(cls.__relations__, rdef, name=name)
+            _add_relation(cls.__relations__, rdef, name=name)
 
     @classmethod
     def insert_relation_after(cls, afterrelname, name, rdef):
@@ -522,8 +535,9 @@ class EntityType(Definition, metaclass=m
                 break
         else:
             raise BadSchemaDefinition("can't find %s relation on %s" % (
-                    afterrelname, cls))
-        _add_relation(cls.__relations__, rdef, name, i+1)
+                afterrelname, cls
+            ))
+        _add_relation(cls.__relations__, rdef, name, i + 1)
 
     @classmethod
     def remove_relation(cls, name):
@@ -611,10 +625,10 @@ class ComputedRelation(RelationType):
 
 class RelationDefinition(Definition):
     # FIXME reader magic forbids to define a docstring...
-    #"""a relation is defined by a name, the entity types that can be
-    #subject or object the relation, the cardinality, the constraints
-    #and the symmetric property.
-    #"""
+    # """a relation is defined by a name, the entity types that can be
+    # subject or object the relation, the cardinality, the constraints
+    # and the symmetric property.
+    # """
 
     subject = MARKER
     object = MARKER
@@ -743,6 +757,7 @@ class RelationDefinition(Definition):
                 _copy_attributes(self, rdef, rdefprops)
                 schema.add_relation_def(rdef)
 
+
 def _actual_types(schema, etype):
     if etype == '*':
         return _pow_etypes(schema)
@@ -755,6 +770,7 @@ def _actual_types(schema, etype):
                            'Hence, %r is not acceptable.' % etype)
     return (etype,)
 
+
 def _pow_etypes(schema):
     for eschema in schema.entities():
         if eschema.final:
diff --git a/yams/constraints.py b/yams/constraints.py
--- a/yams/constraints.py
+++ b/yams/constraints.py
@@ -512,6 +512,7 @@ FORMAT_CONSTRAINT = FormatConstraint()
 class MultipleStaticVocabularyConstraint(StaticVocabularyConstraint):
     """Enforce a list of values to be in a predefined set vocabulary."""
     # XXX never used
+
     def check(self, entity, rtype, values):
         """return true if the values satisfy the constraint, else false"""
         vocab = self.vocabulary(entity=entity)
diff --git a/yams/diff.py b/yams/diff.py
--- a/yams/diff.py
+++ b/yams/diff.py
@@ -42,40 +42,47 @@ def quoted(obj):
             return '"%s"' % obj
     return "'%s'" % obj
 
+
 class attr_scope(object):
     indentation = 2
     spacer = ''
     nextline = ','
 
+
 class class_scope(object):
     indentation = 1
     spacer = ' '
     nextline = ''
 
+
 def identity(x):
     return x
 
+
 def format_props(props, scope, ignore=()):
     out = []
     for prop, val in sorted(props.items()):
         if prop in ignore:
             continue
-        out.append('\t' * scope.indentation +
-                   '%s%s=%s%s' % (prop, scope.spacer, scope.spacer, val))
+        out.append('\t' * scope.indentation
+                   + '%s%s=%s%s' % (prop, scope.spacer, scope.spacer, val))
     return ('%s\n' % scope.nextline).join(out)
 
+
 def format_expression(expr):
     mainvars = expr.mainvars - set('SUXO')
     return '%s(%s%s)' % (expr.__class__.__name__,
                          quoted(expr.expression),
                          ','.join(mainvars) if mainvars else '')
 
+
 def format_tuple(iterator):
     out = []
     for thing in iterator:
         out.append(thing)
     return '(%s)' % ','.join(out)
 
+
 def format_perms(perms, scope, isdefault):
     out = []
     for p in ('read', 'add', 'update', 'delete'):
@@ -86,11 +93,12 @@ def format_perms(perms, scope, isdefault
                         quoted(p),
                         format_tuple(format_expression(r)
                                      if not isinstance(r, str) else quoted(r)
-                              for r in sorted(rule))))
+                                     for r in sorted(rule))))
     return ' {%s\n%s\n%s}' % (' # default perms' if isdefault else '',
                               ',\n'.join(out),
                               '\t' * scope.indentation)
 
+
 def format_constraint(cstr):
     cclass = cstr.__class__.__name__
     if 'RQL' in cclass:
@@ -106,9 +114,11 @@ def format_constraint(cstr):
         return str(cstr)
     return ''.join(out)
 
+
 def nullhandler(relation, perms):
     return perms, False
 
+
 def properties_from(relation, permissionshandler=nullhandler):
     """return a dictionary containing properties of an attribute
     or a relation (if specified with is_relation option)"""
@@ -128,10 +138,10 @@ def properties_from(relation, permission
             prop = 'required'
             val = val[0] == '1'
             if not val:
-                continue # don't emit 'required = False' props
+                continue  # don't emit 'required = False' props
         elif prop in ('indexed', 'fulltextindexed', 'uid', 'internationalizable'):
             if not val:
-                continue # don't emit 'prop = False' props
+                continue  # don't emit 'prop = False' props
         elif prop == 'constraints':
             other = []
             for constraint in val:
@@ -159,16 +169,17 @@ def properties_from(relation, permission
         if prop == 'default':
             if not isinstance(val, bool):
                 if not val:
-                    continue # default = ''
+                    continue  # default = ''
         elif prop in ('description', 'cardinality', 'composite'):
             if val:
                 val = quoted(val)
-            else: # let's skip empty strings
+            else:  # let's skip empty strings
                 continue
 
         ret[prop] = val
     return ret
 
+
 def schema2descr(schema, permissionshandler, ignore=()):
     """convert a yams schema into a text description"""
     output = []
@@ -177,9 +188,9 @@ def schema2descr(schema, permissionshand
     for entity in sorted(schema.entities()):
         if entity.final:
             continue
-        output.append('class %s(EntityType):\n' % entity.type )
+        output.append('class %s(EntityType):\n' % entity.type)
         perms, isdefault = permissionshandler(entity, entity.permissions)
-        output.append('\t__permissions__ = %s\n\n' %format_perms(perms, class_scope, isdefault))
+        output.append('\t__permissions__ = %s\n\n' % format_perms(perms, class_scope, isdefault))
 
         attributes = [(attr[0].type,
                        attr[1].type,
@@ -189,11 +200,11 @@ def schema2descr(schema, permissionshand
             if attr_name in ignore:
                 continue
             output.append('\t%s = %s(\n%s)\n\n' % (attr_name,
-                                              attr_type,
-                                              format_props(attr_props, attr_scope, ignore)))
-        subject_relations = [(rel[0].type, # rtype
-                              [r.type for r in rel[1]], # etype targets
-                              properties_from(entity.rdef(rel[0].type), permissionshandler)) # properties
+                                                   attr_type,
+                                                   format_props(attr_props, attr_scope, ignore)))
+        subject_relations = [(rel[0].type,  # rtype
+                              [r.type for r in rel[1]],  # etype targets
+                              properties_from(entity.rdef(rel[0].type), permissionshandler))  # properties
                              for rel in sorted(entity.relation_definitions())
                              if rel[2] == 'subject']
         for rtype, targettypes, props in subject_relations:
@@ -207,7 +218,7 @@ def schema2descr(schema, permissionshand
                 multirtypes.append(rtype)
                 continue
             output.append('\t%s = SubjectRelation(%s\n%s)\n\n' %
-                       (rtype, ttypes_out, format_props(props, attr_scope, ignore)) )
+                          (rtype, ttypes_out, format_props(props, attr_scope, ignore)))
         output.append('\n\n')
 
     # Handle multi-rdef relation types
@@ -225,12 +236,14 @@ def schema2descr(schema, permissionshand
             output.append('\n\n')
     return ''.join(output)
 
+
 def schema2file(schema, output, permissionshandler, ignore=()):
     """Save schema description of schema find
     in directory schema_dir into output file"""
     with open(output, 'w') as description_file:
         description_file.write(schema2descr(schema, permissionshandler, ignore))
 
+
 def schema_diff(schema1, schema2, permissionshandler=nullhandler, diff_tool=None, ignore=()):
     """schema 1 and 2 are CubicwebSchema
     diff_tool is the name of tool use for file comparison
@@ -241,32 +254,33 @@ def schema_diff(schema1, schema2, permis
     schema2file(schema1, output1, permissionshandler, ignore)
     schema2file(schema2, output2, permissionshandler, ignore)
     if diff_tool:
-        cmd = "%s %s %s" %(diff_tool,
-                           output1, output2)
-        process = subprocess.Popen(cmd, shell=True)
+        cmd = "%s %s %s" % (diff_tool,
+                            output1, output2)
+        subprocess.Popen(cmd, shell=True)
     else:
         print("description files save in %s and %s" % (output1, output2))
     print(output1, output2)
     return output1, output2
 
+
 if __name__ == "__main__":
     from optparse import OptionParser
 
     parser = OptionParser()
     parser.add_option("-f", "--first-schema", dest="schema1",
-                      help= "Specify the directory of the first schema")
+                      help="Specify the directory of the first schema")
     parser.add_option("-s", "--second-schema", dest="schema2",
-                      help= "Specify the directory of the second schema")
+                      help="Specify the directory of the second schema")
     parser.add_option("-d", "--diff-tool", dest="diff_tool",
-                      help= "Specify the name of the diff tool")
+                      help="Specify the name of the diff tool")
     (options, args) = parser.parse_args()
     if options.schema1 and options.schema2:
         schema1 = SchemaLoader().load([options.schema1])
         schema2 = SchemaLoader().load([options.schema2])
         output1, output2 = schema_diff(schema1, schema2)
         if options.diff_tool:
-            cmd = "%s %s %s" %(options.diff_tool,
-                               output1, output2)
+            cmd = "%s %s %s" % (options.diff_tool,
+                                output1, output2)
             process = subprocess.Popen(cmd, shell=True)
         else:
             print("description files save in %s and %s" % (output1, output2))
diff --git a/yams/interfaces.py b/yams/interfaces.py
--- a/yams/interfaces.py
+++ b/yams/interfaces.py
@@ -64,6 +64,7 @@ class IRelationSchema(Interface):  # (IR
     """A relation is a named ordered link between two entities.
     A relation schema defines the possible types of both extremities.
     """
+
     def associations(self, schema=None):
         """return a list of (subject_type, [object_types]) defining between
         which types this relation may exists
diff --git a/yams/reader.py b/yams/reader.py
--- a/yams/reader.py
+++ b/yams/reader.py
@@ -49,7 +49,7 @@ for objname in dir(constraints):
     obj = getattr(constraints, objname)
     try:
         if issubclass(obj, constraints.BaseConstraint) and (
-            not obj is constraints.BaseConstraint):
+                obj is not constraints.BaseConstraint):
             CONSTRAINTS[objname] = obj
     except TypeError:
         continue
@@ -170,6 +170,7 @@ class SchemaLoader(object):
 
     # has to be overridable sometimes (usually for test purpose)
     main_schema_directory = 'schema'
+
     def get_schema_files(self, directory):
         """return an ordered list of files defining a schema
 
@@ -204,7 +205,7 @@ class SchemaLoader(object):
                 if (isinstance(obj, type)
                     and issubclass(obj, buildobjs.Definition)
                     and obj.__module__ == modname
-                    and not name.startswith('_')):
+                        and not name.startswith('_')):
                     objects_to_add.add(obj)
             for obj in objects_to_add:
                 self.add_definition(obj, filepath)
@@ -245,17 +246,17 @@ class SchemaLoader(object):
             assert mpath.startswith(fpath), (
                 modname, filepath, module.__file__)
         else:
-            fglobals = {} # self.context.copy()
+            fglobals = {}  # self.context.copy()
             fglobals['__file__'] = filepath
             fglobals['__name__'] = modname
             package = '.'.join(modname.split('.')[:-1])
-            if package and not package in sys.modules:
+            if package and package not in sys.modules:
                 __import__(package)
             with open(filepath) as f:
                 try:
                     code = compile(f.read(), filepath, 'exec')
                     exec(code, fglobals)
-                except:
+                except Exception:
                     print('exception while reading %s' % filepath, file=sys.stderr)
                     raise
             fglobals['__file__'] = filepath
@@ -270,25 +271,30 @@ class SchemaLoader(object):
                 module.__path__ = [dirname(filepath)]
         return (modname, module)
 
+
 # XXX backward compatibility to prevent changing cw.schema and cw.test.unittest_schema (3.12.+)
 PyFileReader = SchemaLoader
 PyFileReader.__init__ = lambda *x: None
 
+
 def fill_schema_from_namespace(schema, items, **kwargs):
     erdefs = {}
-    for name, obj in items:
+    for _, obj in items:
         if (isinstance(obj, type) and issubclass(obj, buildobjs.Definition)
-            and obj not in (buildobjs.Definition, buildobjs.RelationDefinition, buildobjs.EntityType)):
+                and obj not in (buildobjs.Definition, buildobjs.RelationDefinition, buildobjs.EntityType)):
             obj.expand_type_definitions(erdefs)
     fill_schema(schema, erdefs, **kwargs)
 
+
 def build_schema_from_namespace(items):
     schema = schemamod.Schema('noname')
     fill_schema_from_namespace(schema, items)
     return schema
 
+
 class _Context(object):
     def __init__(self):
         self.defined = {}
 
+
 context = _Context()
diff --git a/yams/schema.py b/yams/schema.py
--- a/yams/schema.py
+++ b/yams/schema.py
@@ -15,6 +15,8 @@
 #
 # You should have received a copy of the GNU Lesser General Public License along
 # with yams. If not, see <http://www.gnu.org/licenses/>.
+from logilab.common.logging_ext import set_log_methods
+import logging
 """Classes to define generic Entities/Relations schemas."""
 
 __docformat__ = "restructuredtext en"
@@ -38,12 +40,14 @@ from yams.constraints import BASE_CHECKE
 
 _ = str
 
+
 def role_name(rtype, role):
     """function to use for qualifying attribute / relation in ValidationError
     errors'dictionnary
     """
     return '%s-%s' % (rtype, role)
 
+
 def rehash(dictionary):
     """this function manually builds a copy of `dictionary` but forces
     hash values to be recomputed. Note that dict(d) or d.copy() don't
@@ -76,14 +80,15 @@ def rehash(dictionary):
     """
     return dict(item for item in dictionary.items())
 
+
 def _format_properties(props):
     res = [('%s=%s' % item) for item in props.items() if item[1]]
     return ','.join(res)
 
+
 class ERSchema(object):
     """Base class shared by entity and relation schema."""
 
-
     def __init__(self, schema=None, erdef=None):
         """
         Construct an ERSchema instance.
@@ -129,6 +134,7 @@ class ERSchema(object):
 
 class PermissionMixIn(object):
     """mixin class for permissions handling"""
+
     def action_permissions(self, action):
         return self.permissions[action]
 
@@ -145,13 +151,13 @@ class PermissionMixIn(object):
             assert action in self.ACTIONS, \
                 'unknown action %s for %s' % (action, self)
             assert isinstance(groups, tuple), \
-                   ('permission for action %s of %s isn\'t a tuple as '
-                    'expected' % (action, self))
+                ('permission for action %s of %s isn\'t a tuple as '
+                 'expected' % (action, self))
         if self.final:
             self.advertise_new_add_permission()
         for action in self.ACTIONS:
             assert action in self.permissions, \
-                   'missing expected permissions for action %s for %s' % (action, self)
+                'missing expected permissions for action %s for %s' % (action, self)
 
 
 # Schema objects definition ###################################################
@@ -184,7 +190,7 @@ class EntitySchema(PermissionMixIn, ERSc
             self.final = self.type in BASE_TYPES
             self.permissions = rdef.__permissions__.copy()
             self._unique_together = getattr(rdef, '__unique_together__', [])
-        else: # this happens during deep copy (cf. ERSchema.__deepcopy__)
+        else:  # this happens during deep copy (cf. ERSchema.__deepcopy__)
             self._specialized_type = None
             self._specialized_by = []
 
@@ -216,7 +222,6 @@ class EntitySchema(PermissionMixIn, ERSc
     def advertise_new_add_permission(self):
         pass
 
-
     # schema building methods #################################################
 
     def add_subject_relation(self, rschema):
@@ -245,7 +250,7 @@ class EntitySchema(PermissionMixIn, ERSc
 
     # IEntitySchema interface #################################################
 
-    ## navigation ######################
+    # navigation ######################
 
     def specializes(self):
         if self._specialized_type:
@@ -379,7 +384,7 @@ class EntitySchema(PermissionMixIn, ERSc
     def default(self, rtype):
         """return the default value of a subject relation"""
         rdef = self.rdef(rtype, takefirst=True)
-        default =  rdef.default
+        default = rdef.default
         if callable(default):
             default = default()
         if default is MARKER:
@@ -394,7 +399,7 @@ class EntitySchema(PermissionMixIn, ERSc
         """
         return bool(self.rdef(rtype).constraint_by_class(UniqueConstraint))
 
-    ## metadata attributes #############
+    # metadata attributes #############
 
     @cached
     def meta_attributes(self):
@@ -468,7 +473,7 @@ class EntitySchema(PermissionMixIn, ERSc
             if rschema.fulltext_container == 'subject':
                 yield rschema, 'subject'
 
-    ## resource accessors ##############
+    # resource accessors ##############
 
     def is_subobject(self, strict=False, skiprels=()):
         """return True if this entity type is contained by another. If strict,
@@ -492,7 +497,7 @@ class EntitySchema(PermissionMixIn, ERSc
                     return True
         return False
 
-    ## validation ######################
+    # validation ######################
 
     def check(self, entity, creation=False, _=None, relations=None):
         """check the entity and raises an ValidationError exception if it
@@ -534,9 +539,9 @@ class EntitySchema(PermissionMixIn, ERSc
             rtype = rschema.type
             if not aschema.check_value(value):
                 errors[qname] = _('incorrect value (%(KEY-value)r) for type "%(KEY-type)s"')
-                msgargs[qname+'-value'] = value
-                msgargs[qname+'-type'] = aschema.type
-                i18nvalues.append(qname+'-type')
+                msgargs[qname + '-value'] = value
+                msgargs[qname + '-type'] = aschema.type
+                i18nvalues.append(qname + '-type')
                 if isinstance(value, bytes) and aschema == 'String':
                     errors[qname] += '; you might want to try unicode'
                 continue
@@ -629,7 +634,7 @@ class RelationDefinitionSchema(Permissio
     def __str__(self):
         if self.object.final:
             return 'attribute %s.%s[%s]' % (
-            self.subject, self.rtype, self.object)
+                self.subject, self.rtype, self.object)
         return 'relation %s %s %s' % (
             self.subject, self.rtype, self.object)
 
@@ -657,7 +662,6 @@ class RelationDefinitionSchema(Permissio
                           'set to %s by default, but you must make it explicit' %
                           (self, defaultaddperms), DeprecationWarning)
 
-
     @classmethod
     def rproperty_defs(cls, desttype):
         """return a dictionary mapping property name to its definition for each
@@ -687,8 +691,8 @@ class RelationDefinitionSchema(Permissio
 
     def dump(self, subject, object):
         return self.__class__(subject, self.rtype, object,
-                                        self.package,
-                                        self.__dict__)
+                              self.package,
+                              self.__dict__)
 
     def role_cardinality(self, role):
         return self.cardinality[role == 'object']
@@ -714,13 +718,12 @@ class RelationDefinitionSchema(Permissio
     def check_permission_definitions(self):
         """check permissions are correctly defined"""
         super(RelationDefinitionSchema, self).check_permission_definitions()
-        if (self.final and self.formula and
-                (self.permissions['add'] or self.permissions['update'])):
+        if (self.final and self.formula
+                and (self.permissions['add'] or self.permissions['update'])):
             raise BadSchemaDefinition(
                 'Cannot set add/update permissions on computed %s' % self)
 
 
-
 class RelationSchema(ERSchema):
     """A relation is a named and oriented link between two entities.
     A relation schema defines the possible types of both extremities.
@@ -740,8 +743,9 @@ class RelationSchema(ERSchema):
     rule = None
     # if this relation is an attribute relation
     final = False
-    permissions = None # only when rule is not None, for later propagation to
-                       # computed relation definitions
+    # only when rule is not None, for later propagation to
+    # computed relation definitions
+    permissions = None
     rdef_class = RelationDefinitionSchema
 
     def __init__(self, schema=None, rdef=None, **kwargs):
@@ -809,10 +813,10 @@ class RelationSchema(ERSchema):
                 continue
             if final != eschema.final:
                 if final:
-                    feschema, nfeschema = subjschema, self.subjects()[0]
+                    feschema, _ = subjschema, self.subjects()[0]
                     frschema, nfrschema = objschema, eschema
                 else:
-                    feschema, nfeschema = self.subjects()[0], subjschema
+                    feschema, _ = self.subjects()[0], subjschema
                     frschema, nfrschema = eschema, objschema
                 msg = ("ambiguous relation: '%(feschema)s.%(rtype)s' is final (%(frschema)s) "
                        "but not '%(nfeschema)s.%(rtype)s' (%(nfrschema)s)")
@@ -857,10 +861,10 @@ class RelationSchema(ERSchema):
 
     def _update(self, subjectschema, objectschema):
         objtypes = self._subj_schemas.setdefault(subjectschema, [])
-        if not objectschema in objtypes:
+        if objectschema not in objtypes:
             objtypes.append(objectschema)
         subjtypes = self._obj_schemas.setdefault(objectschema, [])
-        if not subjectschema in subjtypes:
+        if subjectschema not in subjtypes:
             subjtypes.append(subjectschema)
 
     def del_relation_def(self, subjschema, objschema, _recursing=False):
@@ -1236,7 +1240,7 @@ class Schema(object):
         try:
             return self._relations[rtype]
         except KeyError:
-            raise KeyError('No relation named %s in schema'%rtype)
+            raise KeyError('No relation named %s in schema' % rtype)
 
     def finalize(self):
         """Finalize schema
@@ -1247,7 +1251,5 @@ class Schema(object):
         self.infer_specialization_rules()
 
 
-import logging
-from logilab.common.logging_ext import set_log_methods
 LOGGER = logging.getLogger('yams')
 set_log_methods(Schema, LOGGER)
diff --git a/yams/schema2dot.py b/yams/schema2dot.py
--- a/yams/schema2dot.py
+++ b/yams/schema2dot.py
@@ -21,7 +21,8 @@
 from __future__ import print_function
 __docformat__ = "restructuredtext en"
 
-import sys, os
+import sys
+import os
 import os.path as osp
 from itertools import cycle
 
@@ -32,22 +33,23 @@ CARD_MAP = {'?': '0..1',
             '*': '0..n',
             '+': '1..n'}
 
+
 class SchemaDotPropsHandler(object):
     def __init__(self, visitor):
         self.visitor = visitor
         # FIXME: colors are arbitrary
-        self._colors = cycle( ('#aa0000', '#00aa00', '#0000aa',
-                                 '#000000', '#888888') )
+        self._colors = cycle(('#aa0000', '#00aa00', '#0000aa',
+                              '#000000', '#888888'))
         self.nextcolor = lambda: next(self._colors)
 
     def node_properties(self, eschema):
         """return default DOT drawing options for an entity schema"""
-        label = ['{',eschema.type,'|']
+        label = ['{', eschema.type, '|']
         label.append(r'\l'.join(rel.type for rel in eschema.ordered_relations()
                                 if rel.final and self.visitor.should_display_attr(eschema, rel)))
-        label.append(r'\l}') # trailing \l ensure alignement of the last one
-        return {'label' : ''.join(label), 'shape' : "record",
-                'fontname' : "Courier", 'style' : "filled"}
+        label.append(r'\l}')  # trailing \l ensure alignement of the last one
+        return {'label': ''.join(label), 'shape': "record",
+                'fontname': "Courier", 'style': "filled"}
 
     def edge_properties(self, rschema, subjnode, objnode):
         """return default DOT drawing options for a relation schema"""
@@ -55,7 +57,7 @@ class SchemaDotPropsHandler(object):
         # we get there because we want to draw a specialization arrow anyway
         if rschema is None:
             kwargs = {'label': 'Parent class',
-                      'color' : 'grey',  'style' : 'filled',
+                      'color': 'grey', 'style': 'filled',
                       'arrowhead': 'empty'}
         elif rschema.symmetric:
             # symmetric rels are handled differently, let yams decide what's best
@@ -64,9 +66,8 @@ class SchemaDotPropsHandler(object):
                       'dir': 'both', 'arrowhead': 'normal', 'arrowtail': 'normal'}
         else:
             kwargs = {'label': rschema.type,
-                      'color' : 'black',  'style' : 'filled'}
+                      'color': 'black', 'style': 'filled'}
             rdef = rschema.rdef(subjnode, objnode)
-            composite = rdef.composite
             if rdef.composite == 'subject':
                 kwargs['arrowhead'] = 'none'
                 kwargs['arrowtail'] = 'diamond'
@@ -86,7 +87,7 @@ class SchemaDotPropsHandler(object):
         # dot label decoration is just awful (1 line underlining the label
         # + 1 line going to the closest edge spline point)
         kwargs['decorate'] = 'false'
-        #kwargs['labelfloat'] = 'true'
+        # kwargs['labelfloat'] = 'true'
         return kwargs
 
 
@@ -101,7 +102,7 @@ class SchemaVisitor(object):
         return not (erschema.final or erschema in self.skiptypes)
 
     def should_display_attr(self, eschema, rschema):
-        return not rschema in self.skiptypes
+        return rschema not in self.skiptypes
 
     def display_rel(self, rschema, setype, tetype):
         if (rschema, setype, tetype) in self._done:
@@ -187,7 +188,6 @@ class OneHopRSchemaVisitor(SchemaVisitor
         super(OneHopRSchemaVisitor, self).__init__(skiptypes)
         nodes = set()
         edges = set()
-        done = set()
         for seschema in rschema.subjects():
             nodes.add((seschema.type, seschema))
             for oeschema in rschema.objects(seschema.type):
@@ -212,10 +212,10 @@ def schema2dot(schema=None, outputfile=N
                                           ratio='compress', size=size,
                                           renderer='dot',
                                           additionnal_param={
-                                              'overlap':'false',
-                                              'splines':'true',
-                                              #'polylines':'true',
-                                              'sep':'0.2'
+                                              'overlap': 'false',
+                                              'splines': 'true',
+                                              # 'polylines':'true',
+                                              'sep': '0.2'
                                           }))
     return generator.generate(visitor, prophdlr, outputfile)
 
diff --git a/yams/tools.py b/yams/tools.py
--- a/yams/tools.py
+++ b/yams/tools.py
@@ -14,15 +14,17 @@ from yams import schema2dot
 from yams.reader import SchemaLoader
 from yams._exceptions import *
 
+
 def _error(file=None, line=None, msg=''):
     if file is None:
         file = sys.argv[1]
     if line is None:
-        line=''
+        line = ''
     else:
         line = str(line)
     print(':'.join(('E', file, line, msg)), file=sys.stderr)
 
+
 def check_schema():
     config = Configuration(
         usage="yams-check [[[...] deps] deps] apps",
@@ -32,31 +34,32 @@ def check_schema():
     if not dirnames:
         print(config.help(), file=sys.stderr)
         return 2
-    for dir in dirnames:
-        assert exists(dir), dir
+    for dir_ in dirnames:
+        assert exists(dir_), dir_
     try:
         SchemaLoader().load(dirnames)
         return 0
     except Exception as ex:
         tb_offset = getattr(ex, 'tb_offset', 0)
-        filename, lineno, func, text = extract_tb(sys.exc_traceback)[-1-tb_offset]
+        filename, lineno, _, _ = extract_tb(sys.exc_traceback)[-1 - tb_offset]
         if hasattr(ex, "schema_files"):
             filename = ', '.join(ex.schema_files)
-        _error(filename, lineno,"%s -> %s" % (ex.__class__.__name__, ex))
+        _error(filename, lineno, "%s -> %s" % (ex.__class__.__name__, ex))
         return 2
 
+
 def schema_image():
-    options = [('output-file', {'type':'file', 'default': None,
-                 'metavar': '<file>', 'short':'o', 'help':'output image file'}),
-               ('viewer', {'type': 'string', 'default':"rsvg-view", 'short': "w", 'metavar':'<cmd>',
-                 'help':'command use to view the generated file (empty for none)'}),
-               ('lib-dir', {'type': 'string', 'short': "L", 'metavar':'<dir>',
-                 'help':'directory to look for schema dependancies'}),
-              ]
+    options = [('output-file', {'type': 'file', 'default': None,
+                'metavar': '<file>', 'short': 'o', 'help': 'output image file'}),
+               ('viewer', {'type': 'string', 'default': "rsvg-view", 'short': "w", 'metavar': '<cmd>',
+                'help': 'command use to view the generated file (empty for none)'}),
+               ('lib-dir', {'type': 'string', 'short': "L", 'metavar': '<dir>',
+                'help': 'directory to look for schema dependancies'}),
+               ]
 
     config = Configuration(options=options,
-        usage="yams-view [-L <lib_dir> | [[[...] deps] deps]] apps",
-        version=version)
+                           usage="yams-view [-L <lib_dir> | [[[...] deps] deps]] apps",
+                           version=version)
     dirnames = config.load_command_line_configuration()
 
     lib_dir = config['lib-dir']
@@ -69,13 +72,12 @@ def schema_image():
         packages = [pkg for pkg in packages if pkg != app_dir]
     elif False:
         glob = globals().copy()
-        execfile(join(app_dir,"__pkginfo__.py"), glob)
-        #dirnames = [ join(lib_dir,dep) for dep in glob['__use__']]+dirnames
-        packages = [ dep for dep in glob['__use__']]
+        execfile(join(app_dir, "__pkginfo__.py"), glob)
+        # dirnames = [ join(lib_dir,dep) for dep in glob['__use__']]+dirnames
+        packages = [dep for dep in glob['__use__']]
 
-
-    for dir in dirnames:
-        assert exists(dir), dir
+    for dir_ in dirnames:
+        assert exists(dir_), dir_
 
     import cubicweb
     cubicweb_dir = dirname(cubicweb.__file__)
@@ -85,13 +87,16 @@ def schema_image():
     class MockConfig(object):
         def packages(self):
             return packages
+
         def packages_path(self):
             return packages
+
         def schemas_lib_dir(self):
-            return join(cubicweb_dir,"schemas")
-        #def apphome(self):
+            return join(cubicweb_dir, "schemas")
+        # def apphome(self):
         #    return lib_dir
         apphome = dirnames[0]
+
         def appid(self):
             "bob"
 
@@ -99,13 +104,14 @@ def schema_image():
 
     schema = schm_ldr.load(MockConfig())
 
-
     out, viewer = config['output-file'], config['viewer']
     if out is None:
         tmp_file = NamedTemporaryFile(suffix=".svg")
         out = tmp_file.name
-    schema2dot.schema2dot(schema, out, #size=size,
-        skiprels=("identity",), skipentities=("Person","AbstractPerson","Card","AbstractCompany","Company","Division"))
+    schema2dot.schema2dot(schema, out,  # size=size,
+                          skiprels=("identity",),
+                          skipentities=("Person", "AbstractPerson", "Card", "AbstractCompany",
+                                        "Company", "Division"))
     if viewer:
         p = Popen((viewer, out))
         p.wait()
diff --git a/yams/xy.py b/yams/xy.py
--- a/yams/xy.py
+++ b/yams/xy.py
@@ -29,6 +29,7 @@ class XYRegistry(object):
     as dublin core, foaf, doap...
 
     """
+
     def __init__(self):
         self.prefixes = {}
         self._y2x = {}
@@ -79,14 +80,14 @@ class XYRegistry(object):
         self._y2x.setdefault(ykey, []).append(xkey)
         self._x2y.setdefault(xkey, []).append(ykey)
         if not isentity:
-            for dict, key, value in ((self._x2y, xkey, ykey),
-                                     (self._y2x, ykey, xkey)):
+            for dict_, key, value in ((self._x2y, xkey, ykey),
+                                      (self._y2x, ykey, xkey)):
                 if key[0] != '*':
                     wkey = ('*',) + key[1:]
-                    dict.setdefault(wkey, []).append(value)
+                    dict_.setdefault(wkey, []).append(value)
                 if key[2] != '*':
                     wkey = key[:2] + ('*',)
-                    dict.setdefault(wkey, []).append(value)
+                    dict_.setdefault(wkey, []).append(value)
 
     def remove_equivalence(self, yamssnippet, xmlsnippet):
         ykey = self._norm_yams_key(yamssnippet)
@@ -95,14 +96,14 @@ class XYRegistry(object):
         self._y2x.setdefault(ykey, []).remove(xkey)
         self._x2y.setdefault(xkey, []).remove(ykey)
         if not isentity:
-            for dict, key, value in ((self._x2y, xkey, ykey),
-                                     (self._y2x, ykey, xkey)):
+            for dict_, key, value in ((self._x2y, xkey, ykey),
+                                      (self._y2x, ykey, xkey)):
                 if key[0] != '*':
                     wkey = ('*',) + key[1:]
-                    dict.setdefault(wkey, []).remove(value)
+                    dict_.setdefault(wkey, []).remove(value)
                 if key[2] != '*':
                     wkey = key[:2] + ('*',)
-                    dict.setdefault(wkey, []).remove(value)
+                    dict_.setdefault(wkey, []).remove(value)
 
     def yeq(self, xmlsnippet, isentity=False):
         key = self._norm_xml_key(xmlsnippet, isentity)



More information about the cubicweb-devel mailing list