From ac6442a190922d0bbd8f7b19b85bd398a043ce8c Mon Sep 17 00:00:00 2001 From: Radoslav Pitonak Date: Thu, 15 Mar 2018 23:20:59 +0000 Subject: [PATCH 1/2] TryteString.random() use cls.LEN as its default length, when available --- iota/types.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/iota/types.py b/iota/types.py index 70372f9..d19f1cc 100644 --- a/iota/types.py +++ b/iota/types.py @@ -49,7 +49,7 @@ class TryteString(JsonSerializable): IMPORTANT: A TryteString does not represent a numeric value! """ @classmethod - def random(cls, length): + def random(cls, length=None): # type: (int) -> TryteString """ Generates a random sequence of trytes. @@ -60,6 +60,12 @@ def random(cls, length): alphabet = list(itervalues(AsciiTrytesCodec.alphabet)) generator = SystemRandom() + try: + length = length or cls.LEN + except AttributeError: # class has no LEN attribute + if length is None: + raise TypeError("random() missing 1 required positional argument: 'length'") + # :py:meth:`SystemRandom.choices` wasn't added until Python 3.6; # for compatibility, we will continue to use ``choice`` in a loop. # https://docs.python.org/3/library/random.html#random.choices From aae0cf0042bd84799de40c16eac07c29d582132f Mon Sep 17 00:00:00 2001 From: Radoslav Pitonak Date: Mon, 2 Jul 2018 13:54:24 +0100 Subject: [PATCH 2/2] explicit is None check, better error message --- iota/types.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/iota/types.py b/iota/types.py index d19f1cc..26b25ed 100644 --- a/iota/types.py +++ b/iota/types.py @@ -61,10 +61,14 @@ def random(cls, length=None): generator = SystemRandom() try: - length = length or cls.LEN + if length is None: + length = cls.LEN + + if length <= 0: + raise TypeError("length parameter needs to be greater than zero") except AttributeError: # class has no LEN attribute if length is None: - raise TypeError("random() missing 1 required positional argument: 'length'") + raise TypeError("{class_name} does not define a length property".format(class_name=cls.__name__)) # :py:meth:`SystemRandom.choices` wasn't added until Python 3.6; # for compatibility, we will continue to use ``choice`` in a loop.