[PATCH 20 of 24 yams V2] [mypy] type tools.py

Laurent Peuch cortex at worlddomination.be
Wed Mar 4 15:17:56 CET 2020


# HG changeset patch
# User Laurent Peuch <cortex at worlddomination.be>
# Date 1580318073 -3600
#      Wed Jan 29 18:14:33 2020 +0100
# Node ID b1204623450c0b39830db8946df5a0d58abc3ea9
# Parent  6cb63a3499a9633d0748987e747fb8e81c8f0e3d
# Available At https://hg.logilab.org/users/lpeuch/yams
#              hg pull https://hg.logilab.org/users/lpeuch/yams -r b1204623450c
# EXP-Topic type_annotations
[mypy] type tools.py

diff --git a/yams/tools.py b/yams/tools.py
--- a/yams/tools.py
+++ b/yams/tools.py
@@ -12,9 +12,13 @@ from logilab.common.configuration import
 from yams import __version__ as version
 from yams import schema2dot
 from yams.reader import SchemaLoader
+from typing import TypeVar, Optional, Union
+
+AnyStr = TypeVar('AnyStr', str, bytes)
 
 
-def _error(file=None, line=None, msg=''):
+def _error(file: Optional[str] = None, line: Optional[Union[int, str]] = None,
+           msg: str = '') -> None:
     if file is None:
         file = sys.argv[1]
     if line is None:
@@ -24,30 +28,41 @@ def _error(file=None, line=None, msg='')
     print(':'.join(('E', file, line, msg)), file=sys.stderr)
 
 
-def check_schema():
+def check_schema() -> int:
     config = Configuration(
         usage="yams-check [[[...] deps] deps] apps",
         doc="Check the schema of an application.",
         version=version)
+
     dirnames = config.load_command_line_configuration()
+
     if not dirnames:
         print(config.help(), file=sys.stderr)
+
         return 2
+
     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, _, _ = extract_tb(sys.exc_traceback)[-1 - tb_offset]
+
         if hasattr(ex, "schema_files"):
-            filename = ', '.join(ex.schema_files)
+            # mypy: "Exception" has no attribute "schema_files"
+            # but we've added it above in the exception chain and we test it before
+            filename = ', '.join(ex.schema_files)  # type: ignore
+
         _error(filename, lineno, "%s -> %s" % (ex.__class__.__name__, ex))
+
         return 2
 
 
-def schema_image():
+def schema_image() -> int:
     options = [('output-file', {'type': 'file', 'default': None,
                 'metavar': '<file>', 'short': 'o', 'help': 'output image file'}),
                ('viewer', {'type': 'string', 'default': "rsvg-view", 'short': "w",
@@ -60,19 +75,25 @@ def schema_image():
     config = Configuration(options=options,
                            usage="yams-view [-L <lib_dir> | [[[...] deps] deps]] apps",
                            version=version)
-    dirnames = config.load_command_line_configuration()
 
+    dirnames = config.load_command_line_configuration()
     lib_dir = config['lib-dir']
+
     assert lib_dir is not None
+
     if lib_dir is not None:
         app_dir = dirnames[-1]
+
         from cubicweb.cwconfig import CubicWebConfiguration as cwcfg
+
         packages = cwcfg.expand_cubes(dirnames)
         packages = cwcfg.reorder_cubes(packages)
         packages = [pkg for pkg in packages if pkg != app_dir]
     elif False:
         glob = globals().copy()
+
         exec(open(join(app_dir, "__pkginfo__.py")).read(), glob)
+
         # dirnames = [ join(lib_dir,dep) for dep in glob['__use__']]+dirnames
         packages = [dep for dep in glob['__use__']]
 
@@ -102,16 +123,22 @@ def schema_image():
 
     print(MockConfig().packages())
 
-    schema = schm_ldr.load(MockConfig())
+    # mypy: Argument 1 to "load" of "SchemaLoader" has incompatible type "MockConfig";
+    # mypy: expected "Sequence[Tuple[Any, str]]"
+    # mocking
+    schema = schm_ldr.load(MockConfig())  # type: ignore
 
     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"))
+
     if viewer:
         p = Popen((viewer, out))
         p.wait()



More information about the cubicweb-devel mailing list