I'm writing a function that validates array-like container to have correct type, length or to be hashable. Some of conditions may not be used for validation.
def check_container(container, type_=None, length=None, hashable=None):
"""
Validates container to have correct type and length, or hashable parameter.
Arguments:
container {iterable} -- instance to be validated
Keyword Arguments:
type_ {type/tuple of types} -- valid type/type
length {int} -- valid length
hashable {bool} -- if container should be hashable
Returns:
bool -- result of verification
"""
valid = True
if type_ is not None:
valid = valid and isinstance(container, type_)
if length is not None:
valid = valid and len(container) == length
if hashable is not None:
valid = valid and isinstance(container, collections.Hashable)
return valid
I confused by the style I collect all booleans together: valid = valid and other_condition. It doesn't look "pythonic" for me. Any thoughts on how it can be writed more compact, readable and "pythonic way"?
Update
Usage of check_container function in code:
class one:
class BoxToMultiDiscrete:
def __init__(self, bounds, n_bins):
if not check_container(bounds, tuple):
raise TypeError("bounds should be a tuple")
if not check_container(n_bins, tuple, len(bounds[0])):
raise TypeError("n_bins should be a tuple of the same length as boundaries")
low = list(bounds[0])
high = list(bounds[1])
self.bins_list = []
for i in range(len(n_bins)):
bins = np.linspace(low[i], high[i], n_bins[i] - 1)
self.bins_list.append(bins)
def transform(self, input_vector):
if not check_container(input_vector, tuple, len(self.bins_list)):
raise TypeError("input_vector should be a tuple of the same length as n_bins")
output_vector = tuple()
for i in range(len(input_vector)):
digit = np.digitize(input_vector[i], self.bins_list[i])
output_vector += (int(digit),)
return output_vector
class two:
class MultiDiscreteToDiscrete:
def __init__(self, n_bins):
if not check_container(n_bins, tuple):
raise TypeError("n_bins should be a tuple")
self.n_bins = n_bins
self.space_size = np.product(n_bins)
temp = (1,) + n_bins[:-1]
self.cumprod = np.cumprod(temp)
def transform(self, input_vector):
if not check_container(input_vector, tuple, len(self.n_bins)):
raise TypeError("input_vector should be a tuple of the same length as n_bins")
return self._convert(input_vector)
def _convert(self, input_vector):
num = 0
for i, bin in enumerate(input_vector):
num += bin * self.cumprod[i]
return num
P.S. Maybe you can give some feedback about classes too.
typeis a built-in function. Best practice is to avoid shadowing built-in names. \$\endgroup\$isinstance({}, collections.Hashable)always evaluate toFalse? \$\endgroup\$