def __class_getitem__(cls, params):
     if not isinstance(params, tuple):
         params = (params, )
     if not params and cls is not Tuple:
         raise TypeError(
             "Parameter list to {}[...] cannot be empty".format(
                 cls.__qualname__))
     msg = "Parameters to generic types must be types."
     params = tuple(_type_check(p, msg) for p in params)
     if cls is Protocol:
         # Generic can only be subscripted with unique type variables.
         if not all(isinstance(p, TypeVar) for p in params):
             i = 0
             while isinstance(params[i], TypeVar):
                 i += 1
             raise TypeError(
                 "Parameters to Protocol[...] must all be type variables."
                 " Parameter {} is {}".format(i + 1, params[i]))
         if len(set(params)) != len(params):
             raise TypeError(
                 "Parameters to Protocol[...] must all be unique")
     else:
         # Subscripting a regular Generic subclass.
         _check_generic(cls, params)
     return _GenericAlias(cls, params)
Beispiel #2
0
 def __getitem__(self, parameters):
     if parameters == ():
         raise TypingError('cannot take a Bro record of no types.')
     if not isinstance(parameters, tuple):
         parameters = (parameters,)
     parameters = typing._remove_dups_flatten(parameters)  # pylint: disable=protected-access
     if len(parameters) == 1:
         return parameters[0]
     return typing._GenericAlias(self, parameters)  # pylint: disable=protected-access
Beispiel #3
0
 def __getitem__(self, parameters):
     if self._name in ('ClassVar', 'Final'):
         item = _type_check(parameters, f'{self._name} accepts only single type.')
         return _GenericAlias(self, (item,))
     if self._name == 'Union':
         if parameters == ():
             raise TypeError("Cannot take a Union of no types.")
         if not isinstance(parameters, tuple):
             parameters = (parameters,)
         msg = "Union[arg, ...]: each arg must be a type."
         parameters = tuple(_type_check(p, msg) for p in parameters)
         parameters = _remove_dups_flatten(parameters)
         if len(parameters) == 1:
             return parameters[0]
         return _GenericAlias(self, parameters)
     if self._name == 'Optional':
         arg = _type_check(parameters, "Optional[t] requires a single type.")
         return Union[arg, type(None)]
     if self._name == 'Literal':
         # There is no '_type_check' call because arguments to Literal[...] are
         # values, not types.
         return _GenericAlias(self, parameters)
     raise TypeError(f"{self} is not subscriptable")
Beispiel #4
0
def pytype_to_myiatype(pytype):
    """Convert a Python type into a Myia type.

    Arguments:
        pytype: The Python type to convert.
    """
    return _simple_types[pytype]


#############################################
# Extra types compatible with typing module #
#############################################

T = typing.TypeVar('T')

Array = typing._GenericAlias(numpy.ndarray, T)


class External(typing.Generic[T]):
    """Represents a type external to Myia (essentially invalid)."""

    obj: T


__all__ = [
    'Bool',
    'Dict',
    'EnvType',
    'ExceptionType',
    'External',
    'Float',
Beispiel #5
0
import sage.sets.family

def specialize(type, value):
    """
    Return a callable type that takes a GAP handle and make
    """
    if hasattr(type, "specialize"):
        return type.specialize(value)
    else:
        return type

def GenericMeta_specialize(self, value):
    return self.copy_with(tuple(specialize(a, value) for a in self.__args__))
_GenericAlias.specialize = GenericMeta_specialize

Family = _GenericAlias(sage.sets.family.TrivialFamily, typing.T)
class _Facade:
    pass
Facade = _GenericAlias(_Facade, typing.T)

Sage         = attrcall("sage")

# Class for dependent types constructed from a callable value -> type
# 
class DependentType:#(typing._TypingBase): # Singleton
    #__metaclass__ = typing.TypingMeta
    __slots__ = ("name", "specialize")
    # Should be callable?
    def __init__(self, specialize, name):
        self.name = name
        self.specialize = specialize
Beispiel #6
0
 def __class_getitem__(cls, item):
     """Define this to override the patch that koalas performs on pandas.
     https://github.com/databricks/koalas/blob/master/databricks/koalas/__init__.py#L207-L223
     """
     return _GenericAlias(cls, item)
Beispiel #7
0
        bar: fn(tp)

    with pytest.raises(XmlTypeError) as exc_info:
        xml_dataclass(Foo)

    msg = str(exc_info.value)
    assert "Invalid type" in msg
    assert "'bar'" in msg
    cause = exc_info.value.__cause__
    assert isinstance(cause, XmlTypeError)


@pytest.mark.parametrize(
    "tp,err",
    [
        (_GenericAlias(
            list, (int, str)), "List type has invalid number of arguments"),
        (List[Optional[XmlDt1]], "Nested type cannot be optional"),
        (Optional[List[Optional[XmlDt1]]], "Nested type cannot be optional"),
        (Union[XmlDt1, XmlDt2], "different namespaces"),
    ],
)
def test_invalid_field_types_2(tp, err):
    class Foo:
        __ns__ = None
        bar: tp

    with pytest.raises(XmlTypeError) as exc_info:
        xml_dataclass(Foo)

    msg = str(exc_info.value)
    assert "Invalid type" in msg
 def __getitem__(self, parameters):
     return _GenericAlias(self, parameters)
Beispiel #9
0
 def __getitem__(self, parameters):
     item = _type_check(parameters, "Static accepts only single type.")
     return _GenericAlias(self, (item, ))
Beispiel #10
0
 def __class_getitem__(cls, params):
     ty = _GenericAlias(cls.__special_form__, params)
     ty.__apix_param_type__ = cls.__apix_param_type__
     return ty