Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
# aren't compatible with the signature for `func`
bound_expected_args = func_signature.bind(*expected_arg_types).arguments
args = {
name: identifier(name, type_)
for name, type_ in six.iteritems(bound_expected_args)
}
first_guid = client.guid()
result = func(**args)
if returns is not None:
try:
result = returns._promote(result)
except ProxyTypeError as e:
raise ProxyTypeError(
"Cannot promote {} to {}, the expected return type of the function: {}".format(
result, returns.__name__, e
)
)
else:
result = proxify(result)
return type(result)._from_graft(
client.function_graft(
result, *tuple(func_signature.parameters), first_guid=first_guid
)
)
else:
if not isinstance(dct, abc.Mapping):
raise ProxyTypeError("Expected a mapping, got {}".format(dct))
dct = dct.copy()
dct.update(kwargs)
# TODO(gabe): numer of copies of source dict could definitely be reduced here
is_str_dict = issubclass(kt, Str)
promoted = {} if is_str_dict else []
for key, val in six.iteritems(dct):
try:
promoted_key = kt._promote(key)
except ProxyTypeError:
raise ProxyTypeError(
"Expected Dict keys of type {}, but got {}".format(kt, key)
)
try:
promoted_val = vt._promote(val)
except ProxyTypeError:
raise ProxyTypeError(
"Expected Dict values of type {}, but got {}".format(vt, val)
)
if is_str_dict:
promoted[key] = promoted_val
# note we use the unpromoted key, which should be a string
# this is an optimization that produces a cleaner graph for the case of string-keyed dicts
else:
promoted += [promoted_key, promoted_val]
# for non-string dicts, we just give varargs of key, value, key, value, ...
# since that's a much simpler graft representation than constructing a list
def __getitem__(self, item):
# TODO(gabe): slices
# TODO(gabe): cache
# TODO(gabe): no nested traceback on out-of-bounds index?
try:
promoted_item = Int._promote(item)
except ProxyTypeError:
raise ProxyTypeError(
"Tuple indicies must be integers, not {}".format(type(item))
)
item_type = self._type_params[item] if isinstance(item, int) else Any
# ^ if `idx` is a proxy Int, we don't know which index we're selecting and therefore the return type
return item_type._from_apply("getitem", self, promoted_item)
elif isinstance(obj, float):
return Float(obj)
elif isinstance(obj, bool):
return Bool(obj)
elif isinstance(obj, str):
return Str(obj)
elif obj is None:
return NoneType(obj)
elif isinstance(obj, (datetime.datetime, datetime.date)):
return Datetime._promote(obj)
elif isinstance(obj, datetime.timedelta):
return Timedelta._promote(obj)
else:
try:
return Any._promote(obj)
except ProxyTypeError:
raise NotImplementedError(
"Cannot automatically convert to a Proxytype. "
"Please manually construct the appropriate container type "
"and initialize it with your object. Value: {!r}".format(obj)
)
def __init__(self, iterable):
value_types = self._type_params
if value_types is None:
raise TypeError(
"Cannot instantiate a generic Tuple; the item types must be specified (like `Tuple[Int, Float]`)"
)
# TODO: copy constructor
if not isinstance(iterable, abc.Iterable):
raise ProxyTypeError("Expected an iterable, got {}".format(iterable))
try:
length = len(iterable)
except TypeError:
iterable = tuple(iterable)
length = len(iterable)
if length != len(self._type_params):
raise ProxyTypeError(
"To construct {}, expected an iterable of {} items, "
"but got {} items".format(
type(self).__name__, len(self._type_params), length
)
)
def checker_promoter(i, x):
promoted_kwargs = {}
for field_name, val in six.iteritems(kwargs):
try:
field_cls = type_params[field_name]
except KeyError:
raise ProxyTypeError(
"{} has no field {!r}".format(class_name, field_name)
)
if val is None or isinstance(val, NoneType) and field_name in optional:
continue
try:
promoted_val = field_cls._promote(val)
except ProxyTypeError as e:
raise ProxyTypeError(
"In field {!r} of {}, expected {}, but got {}: {}".format(
field_name, class_name, field_cls, type(val), val
),
e,
)
promoted_kwargs[field_name] = promoted_val
return promoted_kwargs
)
missing_args = (
six.viewkeys(type_params) - six.viewkeys(kwargs) - optional - read_only
)
if len(missing_args) > 0:
raise ProxyTypeError(
"Missing required keyword arguments to {}: {}".format(
class_name, ", ".join(six.moves.map(repr, missing_args))
)
)
provided_read_only_args = six.viewkeys(kwargs) & read_only
if len(provided_read_only_args) > 0:
raise ProxyTypeError(
"Read only keyword argument to {}: {}".format(
class_name, ", ".join(six.moves.map(repr, provided_read_only_args))
)
)
promoted_kwargs = {}
for field_name, val in six.iteritems(kwargs):
try:
field_cls = type_params[field_name]
except KeyError:
raise ProxyTypeError(
"{} has no field {!r}".format(class_name, field_name)
)
if val is None or isinstance(val, NoneType) and field_name in optional:
continue
def __getitem__(self, item):
# TODO: cache
# requires figuring out how to make Delayed objects hashable
kt, vt = self._type_params
try:
item = kt._promote(item)
except ProxyTypeError:
raise ProxyTypeError(
"Dict keys are of type {}, but indexed with {}".format(kt, item)
)
return vt._from_apply("getitem", self, item)
elif callable(function):
arg_types, kwargs_types, return_type = (
self._type_params[:-2],
self._type_params[-2],
self._type_params[-1],
)
if len(kwargs_types) > 0:
raise TypeError(
"Cannot create a Function with optional arguments from a Python function, "
"since optional arguments or conditionals can't be represented with graft. "
"You must delay Python functions into Proxtype Functions that only have positional arguments."
)
self.function = self._delay(function, return_type, *arg_types)
self.graft = self.function.graft
else:
raise ProxyTypeError(
"Function must be a Python callable or string name, "
"not {}".format(function)
)
def checker_promoter(i, x):
cls = value_types[i]
try:
return cls._promote(x)
except ProxyTypeError:
raise ProxyTypeError(
"While constructing {}, expected {} for tuple element {}, but got {!r}".format(
type(self).__name__, cls, i, x
)