Skip to main content
Code Review

Return to Revisions

2 of 2
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/

As @pjz already noted in his answer, type(v0) is slow. However, I would recommend instead to use isinstance. This allows to use your class also with derived types. From help(isinstance):

isinstance(...)
 isinstance(object, class-or-type-or-tuple) -> bool
 
 Return whether an object is an instance of a class or of a subclass thereof.
 With a type as second argument, return whether that is the object's type.
 The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
 isinstance(x, A) or isinstance(x, B) or ... (etc.).

Imagine if I rolled my own int class, Int, which is derived from the base int class:

class Int(int):
 pass

Your RecHash function would not work with this. If you use isinstance(v0, int), though, this would still be working.

if isinstance(v, list) and len(v) == 1:
 isSingleElementList = True
if not isinstance(v, list) or isSingleElementOfList: # if v is a single element
 v0 = v[0] if isSingleElementOfList else v
 type_v0 = type(v0)
 if isinstance(v0, bytearray) or v0.__class__.__name__ == 'bytes':
 return hash(v0)
 if isinstance(v0, int):
 return hash(ToByteArray(v0))
 if isinstance(v0, str):
 return hash(v0.encode('utf-8')) 
else: # if v is a list
 res = bytearray()
 for vi in v:
 res += RecHash(vi) # recursion
 return hash(res) # hash the concatenated hashes

Python has an official style-guide, PEP8. It recommends using lower_case for variable and function names, instead of PascalCase or camelCase.

Graipher
  • 41.7k
  • 7
  • 70
  • 134
default

AltStyle によって変換されたページ (->オリジナル) /