Skip to content

Commit 2f445f7

Browse files
committed
First pass on type hints + some fixes
Some fixes were added to avoid some possible errors found with mypy. See #39
1 parent ae23e48 commit 2f445f7

File tree

9 files changed

+53
-31
lines changed

9 files changed

+53
-31
lines changed

javaobj/utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from __future__ import absolute_import
3131

3232
# Standard library
33+
from typing import Any, Tuple
3334
import logging
3435
import struct
3536
import sys
@@ -76,7 +77,7 @@ def log_error(message, ident=0):
7677

7778

7879
def read_struct(data, fmt_str):
79-
# type: (bytes, str) -> list
80+
# type: (bytes, str) -> Tuple
8081
"""
8182
Reads input bytes and extract the given structure. Returns both the read
8283
elements and the remaining data
@@ -90,7 +91,7 @@ def read_struct(data, fmt_str):
9091

9192

9293
def read_string(data, length_fmt="H"):
93-
# type: (bytes, str) -> UNICODE_TYPE
94+
# type: (bytes, str) -> Tuple[UNICODE_TYPE, bytes]
9495
"""
9596
Reads a serialized string
9697

javaobj/v1/beans.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,8 @@ def __init__(self, classdesc=None):
198198
JavaObject.__init__(self)
199199
self.classdesc = classdesc
200200

201+
def __hash__(self):
202+
return list.__hash__(self)
201203

202204
class JavaByteArray(JavaObject):
203205
"""

javaobj/v1/transformers.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@
3030
import functools
3131

3232
from .beans import JavaObject
33+
from .unmarshaller import JavaObjectUnmarshaller
34+
from ..constants import ClassDescFlags, TerminalCode, TypeCode
3335
from ..utils import (
3436
log_debug,
3537
log_error,
@@ -59,6 +61,9 @@ def __init__(self, unmarshaller):
5961
list.__init__(self)
6062
JavaObject.__init__(self)
6163

64+
def __hash__(self):
65+
return list.__hash__(self)
66+
6267
def __extra_loading__(self, unmarshaller, ident=0):
6368
# type: (JavaObjectUnmarshaller, int) -> None
6469
"""
@@ -110,6 +115,9 @@ def __init__(self, unmarshaller):
110115
dict.__init__(self)
111116
JavaObject.__init__(self)
112117

118+
def __hash__(self):
119+
return dict.__hash__(self)
120+
113121
def __extra_loading__(self, unmarshaller, ident=0):
114122
# type: (JavaObjectUnmarshaller, int) -> None
115123
"""
@@ -128,15 +136,15 @@ def __extra_loading__(self, unmarshaller, ident=0):
128136
"""
129137
# Ignore the blockdata opid
130138
(opid,) = unmarshaller._readStruct(">B")
131-
if opid != unmarshaller.SC_BLOCK_DATA:
139+
if opid != ClassDescFlags.SC_BLOCK_DATA:
132140
raise ValueError("Start of block data not found")
133141

134142
# Read HashMap fields
135143
self.buckets = unmarshaller._read_value(
136-
unmarshaller.TYPE_INTEGER, ident
144+
TypeCode.TYPE_INTEGER, ident
137145
)
138146
self.size = unmarshaller._read_value(
139-
unmarshaller.TYPE_INTEGER, ident
147+
TypeCode.TYPE_INTEGER, ident
140148
)
141149

142150
# Read entries
@@ -147,7 +155,7 @@ def __extra_loading__(self, unmarshaller, ident=0):
147155

148156
# Ignore the end of the blockdata
149157
unmarshaller._read_and_exec_opcode(
150-
ident, [unmarshaller.TC_ENDBLOCKDATA]
158+
ident, [TerminalCode.TC_ENDBLOCKDATA]
151159
)
152160

153161
# Ignore the trailing 0
@@ -165,6 +173,9 @@ def __init__(self, unmarshaller):
165173
set.__init__(self)
166174
JavaObject.__init__(self)
167175

176+
def __hash__(self):
177+
return set.__hash__(self)
178+
168179
def __extra_loading__(self, unmarshaller, ident=0):
169180
# type: (JavaObjectUnmarshaller, int) -> None
170181
"""

javaobj/v1/unmarshaller.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
from __future__ import absolute_import
3737

3838
# Standard library
39+
from typing import Any, Union
3940
import os
4041
import struct
4142

@@ -719,7 +720,7 @@ def do_enum(self, parent=None, ident=0):
719720
return enum
720721

721722
def _read_value(self, raw_field_type, ident, name=""):
722-
# type: (bytes, int, str) -> Any
723+
# type: (Union[bytes, int, TypeCode], int, str) -> Any
723724
"""
724725
Reads the next value, of the given type
725726
@@ -729,15 +730,21 @@ def _read_value(self, raw_field_type, ident, name=""):
729730
:return: The read value
730731
:raise RuntimeError: Unknown field type
731732
"""
732-
if isinstance(raw_field_type, (TypeCode, int)):
733+
if isinstance(raw_field_type, TypeCode):
733734
field_type = raw_field_type
735+
elif isinstance(raw_field_type, int):
736+
field_type = TypeCode(raw_field_type)
734737
else:
735738
# We don't need details for arrays and objects
736-
field_type = TypeCode(ord(raw_field_type[0]))
739+
raw_code = raw_field_type[0]
740+
if isinstance(raw_code, int):
741+
field_type = TypeCode(raw_code)
742+
else:
743+
field_type = TypeCode(ord(raw_code))
737744

738745
if field_type == TypeCode.TYPE_BOOLEAN:
739746
(val,) = self._readStruct(">B")
740-
res = bool(val)
747+
res = bool(val) # type: Any
741748
elif field_type == TypeCode.TYPE_BYTE:
742749
(res,) = self._readStruct(">b")
743750
elif field_type == TypeCode.TYPE_CHAR:

javaobj/v2/beans.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def __init__(self, field_type, name, class_name=None):
202202
# type: (FieldType, str, Optional[JavaString]) -> None
203203
self.type = field_type
204204
self.name = name
205-
self.class_name = class_name # type: JavaString
205+
self.class_name = class_name
206206
self.is_inner_class_reference = False
207207

208208
if self.class_name:

javaobj/v2/core.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -216,15 +216,15 @@ def _dump_instance(self, instance):
216216

217217
if instance.annotations:
218218
lines.append("\tobject annotations:")
219-
for cd, content in instance.annotations.items():
220-
lines.append("\t" + cd.name)
221-
for c in content:
219+
for cd, annotation in instance.annotations.items():
220+
lines.append("\t" + (cd.name or "null"))
221+
for c in annotation:
222222
lines.append("\t\t" + str(c))
223223

224224
if instance.field_data:
225225
lines.append("\tfield data:")
226226
for field, obj in instance.field_data.items():
227-
line = "\t\t" + field.name + ": "
227+
line = "\t\t" + (field.name or "null") + ": "
228228
if isinstance(obj, ParsedJavaContent):
229229
content = obj # type: ParsedJavaContent
230230
h = content.handle
@@ -280,7 +280,7 @@ def _do_null(self, _):
280280
return None
281281

282282
def _read_content(self, type_code, block_data, class_desc=None):
283-
# type: (int, bool) -> ParsedJavaContent
283+
# type: (int, bool, Optional[JavaClassDesc]) -> ParsedJavaContent
284284
"""
285285
Parses the next content
286286
"""
@@ -345,7 +345,7 @@ def _read_classdesc(self):
345345
return self._do_classdesc(type_code)
346346

347347
def _do_classdesc(self, type_code):
348-
# type: (int, bool) -> JavaClassDesc
348+
# type: (int) -> JavaClassDesc
349349
"""
350350
Parses a class description
351351
"""
@@ -432,7 +432,7 @@ def _custom_readObject(self, class_name):
432432
raise ValueError("Custom readObject can not be processed")
433433

434434
def _read_class_annotations(self, class_desc=None):
435-
# type: () -> List[ParsedJavaContent]
435+
# type: (Optional[JavaClassDesc]) -> List[ParsedJavaContent]
436436
"""
437437
Reads the annotations associated to a class
438438
"""
@@ -649,7 +649,7 @@ def _do_array(self, type_code):
649649
"""
650650
cd = self._read_classdesc()
651651
handle = self._new_handle()
652-
if len(cd.name) < 2:
652+
if not cd.name or len(cd.name) < 2:
653653
raise ValueError("Invalid name in array class description")
654654

655655
# ParsedJavaContent type

javaobj/v2/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131

3232

3333
def load(file_object, *transformers, **kwargs):
34-
# type: (IO[bytes], ObjectTransformer) -> Any
34+
# type: (IO[bytes], ObjectTransformer, Any) -> Any
3535
"""
3636
Deserializes Java primitive data and objects serialized using
3737
ObjectOutputStream from a file-like object.
@@ -68,7 +68,7 @@ def load(file_object, *transformers, **kwargs):
6868

6969

7070
def loads(data, *transformers, **kwargs):
71-
# type: (bytes, ObjectTransformer) -> Any
71+
# type: (bytes, ObjectTransformer, Any) -> Any
7272
"""
7373
Deserializes Java objects and primitive data serialized using
7474
ObjectOutputStream from bytes.

javaobj/v2/stream.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@
2626

2727
from __future__ import absolute_import
2828

29-
from typing import Any, IO, List
29+
from typing import Any, IO, List, Tuple
3030
import struct
3131

3232
from ..modifiedutf8 import decode_modified_utf8
33-
from ..utils import unicode_char
33+
from ..utils import unicode_char, UNICODE_TYPE
3434

3535
# ------------------------------------------------------------------------------
3636

@@ -65,7 +65,7 @@ def file_descriptor(self):
6565
return self.__fd
6666

6767
def read(self, struct_format):
68-
# type: (str) -> List[Any]
68+
# type: (str) -> Tuple[Any, ...]
6969
"""
7070
Reads from the input stream, using struct
7171
@@ -103,7 +103,7 @@ def read_ubyte(self):
103103
return self.read(">B")[0]
104104

105105
def read_char(self):
106-
# type: () -> chr
106+
# type: () -> UNICODE_TYPE
107107
"""
108108
Shortcut to read a single `char` (2 bytes)
109109
"""

javaobj/v2/transformers.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
"""
2626

2727
# Standard library
28-
from typing import List, Optional
28+
from typing import List, Optional, Tuple
2929
import functools
3030

3131
# Numpy (optional)
@@ -37,7 +37,8 @@
3737

3838
# Javaobj
3939
from .api import ObjectTransformer
40-
from .beans import JavaInstance
40+
from .beans import JavaInstance, JavaClassDesc
41+
from .core import JavaStreamParser, DataStreamReader
4142
from ..constants import TerminalCode, TypeCode
4243
from ..utils import to_bytes, log_error, log_debug, read_struct, read_string
4344

@@ -137,7 +138,7 @@ class JavaMap(dict, JavaInstance):
137138
Python-Java dictionary/map bridge type
138139
"""
139140

140-
HANDLED_CLASSES = ("java.util.HashMap", "java.util.TreeMap")
141+
HANDLED_CLASSES = ("java.util.HashMap", "java.util.TreeMap") # type: Tuple[str, ...]
141142

142143
def __init__(self):
143144
dict.__init__(self)
@@ -166,7 +167,7 @@ class JavaLinkedHashMap(JavaMap):
166167
Linked has map are handled with a specific block data
167168
"""
168169

169-
HANDLED_CLASSES = "java.util.LinkedHashMap"
170+
HANDLED_CLASSES = ("java.util.LinkedHashMap",)
170171

171172
def load_from_blockdata(self, parser, reader, indent=0):
172173
# type: (JavaStreamParser, DataStreamReader, int) -> bool
@@ -204,7 +205,7 @@ class JavaSet(set, JavaInstance):
204205
Python-Java set bridge type
205206
"""
206207

207-
HANDLED_CLASSES = ("java.util.HashSet", "java.util.LinkedHashSet")
208+
HANDLED_CLASSES = ("java.util.HashSet", "java.util.LinkedHashSet") # type: Tuple[str, ...]
208209

209210
def __init__(self):
210211
set.__init__(self)
@@ -229,7 +230,7 @@ class JavaTreeSet(JavaSet):
229230
Tree sets are handled a bit differently
230231
"""
231232

232-
HANDLED_CLASSES = "java.util.TreeSet"
233+
HANDLED_CLASSES = ("java.util.TreeSet",)
233234

234235
def load_from_instance(self, indent=0):
235236
# type: (int) -> bool

0 commit comments

Comments
 (0)