Added more annotations for mypy

Function declarations that have no type annotations at all will be skipped
by mypy. Adding an explicit `-> None` tells mypy to run on those functions
too.
This commit is contained in:
Sybren A. Stüvel 2018-03-09 14:23:43 +01:00
parent 4dc0dedff1
commit cc06a191a1
2 changed files with 20 additions and 21 deletions

View File

@ -71,7 +71,7 @@ def open_cached(path: pathlib.Path, mode='rb',
@atexit.register @atexit.register
def close_all_cached(): def close_all_cached() -> None:
if not _cached_bfiles: if not _cached_bfiles:
# Don't even log anything when there is nothing to close # Don't even log anything when there is nothing to close
return return
@ -183,7 +183,7 @@ class BlendFile:
fileobj.close() fileobj.close()
raise exceptions.BlendFileError("File is not a blend file", path) raise exceptions.BlendFileError("File is not a blend file", path)
def _load_blocks(self): def _load_blocks(self) -> None:
"""Read the blend file to load its DNA structure to memory.""" """Read the blend file to load its DNA structure to memory."""
self.structs.clear() self.structs.clear()
@ -206,19 +206,19 @@ class BlendFile:
raise exceptions.NoDNA1Block("No DNA1 block in file, not a valid .blend file", raise exceptions.NoDNA1Block("No DNA1 block in file, not a valid .blend file",
self.filepath) self.filepath)
def __repr__(self): def __repr__(self) -> str:
clsname = self.__class__.__qualname__ clsname = self.__class__.__qualname__
if self.filepath == self.raw_filepath: if self.filepath == self.raw_filepath:
return '<%s %r>' % (clsname, self.filepath) return '<%s %r>' % (clsname, self.filepath)
return '<%s %r reading from %r>' % (clsname, self.filepath, self.raw_filepath) return '<%s %r reading from %r>' % (clsname, self.filepath, self.raw_filepath)
def __enter__(self): def __enter__(self) -> 'BlendFile':
return self return self
def __exit__(self, exctype, excvalue, traceback): def __exit__(self, exctype, excvalue, traceback) -> None:
self.close() self.close()
def copy_and_rebind(self, path: pathlib.Path, mode='rb'): def copy_and_rebind(self, path: pathlib.Path, mode='rb') -> None:
"""Change which file is bound to this BlendFile. """Change which file is bound to this BlendFile.
This allows cloning a previously opened file, and rebinding it to reuse This allows cloning a previously opened file, and rebinding it to reuse
@ -240,7 +240,7 @@ class BlendFile:
def is_modified(self) -> bool: def is_modified(self) -> bool:
return self._is_modified return self._is_modified
def mark_modified(self): def mark_modified(self) -> None:
"""Recompess the file when it is closed.""" """Recompess the file when it is closed."""
self.log.debug('Marking %s as modified', self.raw_filepath) self.log.debug('Marking %s as modified', self.raw_filepath)
self._is_modified = True self._is_modified = True
@ -249,7 +249,7 @@ class BlendFile:
assert isinstance(code, bytes) assert isinstance(code, bytes)
return self.code_index[code] return self.code_index[code]
def close(self): def close(self) -> None:
"""Close the blend file. """Close the blend file.
Recompresses the blend file if it was compressed and changed. Recompresses the blend file if it was compressed and changed.
@ -282,7 +282,7 @@ class BlendFile:
except KeyError: except KeyError:
pass pass
def ensure_subtype_smaller(self, sdna_index_curr, sdna_index_next): def ensure_subtype_smaller(self, sdna_index_curr, sdna_index_next) -> None:
# never refine to a smaller type # never refine to a smaller type
curr_struct = self.structs[sdna_index_curr] curr_struct = self.structs[sdna_index_curr]
next_struct = self.structs[sdna_index_next] next_struct = self.structs[sdna_index_next]
@ -462,7 +462,7 @@ class BlendFileBlock:
self.count = blockheader[4] self.count = blockheader[4]
self.file_offset = bfile.fileobj.tell() self.file_offset = bfile.fileobj.tell()
def __repr__(self): def __repr__(self) -> str:
return "<%s.%s (%s), size=%d at %s>" % ( return "<%s.%s (%s), size=%d at %s>" % (
self.__class__.__name__, self.__class__.__name__,
self.dna_type_name, self.dna_type_name,
@ -740,28 +740,28 @@ class BlendFileBlock:
def __getitem__(self, path: dna.FieldPath): def __getitem__(self, path: dna.FieldPath):
return self.get(path) return self.get(path)
def __setitem__(self, item, value): def __setitem__(self, item: bytes, value) -> None:
self.set(item, value) self.set(item, value)
def keys(self) -> typing.Iterator[bytes]: def keys(self) -> typing.Iterator[bytes]:
"""Generator, yields all field names of this block.""" """Generator, yields all field names of this block."""
return (f.name.name_only for f in self.dna_type.fields) return (f.name.name_only for f in self.dna_type.fields)
def values(self): def values(self) -> typing.Iterable[typing.Any]:
for k in self.keys(): for k in self.keys():
try: try:
yield self[k] yield self[k]
except exceptions.NoReaderImplemented as ex: except exceptions.NoReaderImplemented as ex:
yield '<%s>' % ex.dna_type.dna_type_id.decode('ascii') yield '<%s>' % ex.dna_type.dna_type_id.decode('ascii')
def items(self): def items(self) -> typing.Iterable[typing.Tuple[bytes, typing.Any]]:
for k in self.keys(): for k in self.keys():
try: try:
yield (k, self[k]) yield (k, self[k])
except exceptions.NoReaderImplemented as ex: except exceptions.NoReaderImplemented as ex:
yield (k, '<%s>' % ex.dna_type.dna_type_id.decode('ascii')) yield (k, '<%s>' % ex.dna_type.dna_type_id.decode('ascii'))
def items_recursive(self): def items_recursive(self) -> typing.Iterator[typing.Tuple[dna.FieldPath, typing.Any]]:
"""Generator, yields (property path, property value) recursively for all properties.""" """Generator, yields (property path, property value) recursively for all properties."""
for k in self.keys(): for k in self.keys():
yield from self.get_recursive_iter(k, as_str=False) yield from self.get_recursive_iter(k, as_str=False)

View File

@ -4,13 +4,12 @@ import functools
import logging import logging
import pathlib import pathlib
import tempfile import tempfile
import typing import typing
from blender_asset_tracer import trace, bpathlib, blendfile from blender_asset_tracer import trace, bpathlib, blendfile
from blender_asset_tracer.cli import common from blender_asset_tracer.cli import common
from blender_asset_tracer.trace import result from blender_asset_tracer.trace import result
from . import queued_copy from . import queued_copy, transfer
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -75,11 +74,11 @@ class Packer:
self._tmpdir = tempfile.TemporaryDirectory(suffix='-batpack') self._tmpdir = tempfile.TemporaryDirectory(suffix='-batpack')
self._rewrite_in = pathlib.Path(self._tmpdir.name) self._rewrite_in = pathlib.Path(self._tmpdir.name)
def close(self): def close(self) -> None:
"""Clean up any temporary files.""" """Clean up any temporary files."""
self._tmpdir.cleanup() self._tmpdir.cleanup()
def strategise(self): def strategise(self) -> None:
"""Determine what to do with the assets. """Determine what to do with the assets.
Places an asset into one of these categories: Places an asset into one of these categories:
@ -133,7 +132,7 @@ class Packer:
# Like a join, but ignoring the fact that 'path' is absolute. # Like a join, but ignoring the fact that 'path' is absolute.
act.new_path = pathlib.Path(self.target, '_outside_project', *path.parts[1:]) act.new_path = pathlib.Path(self.target, '_outside_project', *path.parts[1:])
def _group_rewrites(self): def _group_rewrites(self) -> None:
"""For each blend file, collect which fields need rewriting. """For each blend file, collect which fields need rewriting.
This ensures that the execute() step has to visit each blend file This ensures that the execute() step has to visit each blend file
@ -158,7 +157,7 @@ class Packer:
return False return False
return True return True
def execute(self): def execute(self) -> None:
"""Execute the strategy.""" """Execute the strategy."""
assert self._actions, 'Run strategise() first' assert self._actions, 'Run strategise() first'
@ -185,7 +184,7 @@ class Packer:
return return
fc.done_and_join() fc.done_and_join()
def _rewrite_paths(self): def _rewrite_paths(self) -> None:
"""Rewrite paths to the new location of the assets. """Rewrite paths to the new location of the assets.
Writes the rewritten blend files to a temporary location. Writes the rewritten blend files to a temporary location.