How to use the pystachio.typing.TypeFactory function in pystachio

To help you get started, we’ve selected a few pystachio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wickman / pystachio / pystachio / basic.py View on Github external
if isinstance(obj._value, Compatibility.real + Compatibility.integer):
      return TypeCheck.success()
    else:
      return TypeCheck.failure("%s not a float" % repr(obj._value))

  @classmethod
  def coerce(cls, value):
    ACCEPTED_SOURCE_TYPES = Compatibility.numeric + Compatibility.stringy
    if not isinstance(value, ACCEPTED_SOURCE_TYPES):
      raise cls.CoercionError(value, cls)
    try:
      return float(value)
    except ValueError:
      raise cls.CoercionError(value, cls)

class FloatFactory(TypeFactory):
  PROVIDES = 'Float'
  @staticmethod
  def create(type_dict, *type_parameters):
    return Float


class Boolean(SimpleObject):
  @classmethod
  def checker(cls, obj):
    assert isinstance(obj, Boolean)
    if isinstance(obj._value, bool):
      return TypeCheck.success()
    else:
      return TypeCheck.failure("%s not a boolean" % repr(obj._value))

  @classmethod
github wickman / pystachio / pystachio / composite.py View on Github external
def __new__(mcs, name, parents, attributes):
    if any(parent.__name__ == 'Struct' for parent in parents):
      type_parameters = StructMetaclass.attributes_to_parameters(attributes)
      return TypeFactory.new({}, 'Struct', name, type_parameters)
    else:
      return type.__new__(mcs, name, parents, attributes)
github wickman / pystachio / pystachio / container.py View on Github external
raise Namable.Unnamable(namable)
        else:
          return namable.in_scope(*self.scopes()).find(ref.rest())

  @classmethod
  def type_factory(cls):
    return 'List'

  @classmethod
  def type_parameters(cls):
    return (cls.TYPE.serialize_type(),)

List = TypeFactory.wrapper(ListFactory)


class MapFactory(TypeFactory):
  PROVIDES = 'Map'

  @staticmethod
  def create(type_dict, *type_parameters):
    assert len(type_parameters) == 2, 'Type parameters: %s' % repr(type_parameters)
    key_klazz, value_klazz = type_parameters
    key_klazz, value_klazz = (TypeFactory.new(type_dict, *key_klazz),
                              TypeFactory.new(type_dict, *value_klazz))
    assert isclass(key_klazz) and isclass(value_klazz)
    assert issubclass(key_klazz, Object) and issubclass(value_klazz, Object)
    return TypeMetaclass('%s%sMap' % (key_klazz.__name__, value_klazz.__name__), (MapContainer,),
      {'KEYTYPE': key_klazz, 'VALUETYPE': value_klazz})


# TODO(wickman) Technically it's possible to do the following:
#
github wickman / pystachio / pystachio / container.py View on Github external
def create(type_dict, *type_parameters):
    assert len(type_parameters) == 2, 'Type parameters: %s' % repr(type_parameters)
    key_klazz, value_klazz = type_parameters
    key_klazz, value_klazz = (TypeFactory.new(type_dict, *key_klazz),
                              TypeFactory.new(type_dict, *value_klazz))
    assert isclass(key_klazz) and isclass(value_klazz)
    assert issubclass(key_klazz, Object) and issubclass(value_klazz, Object)
    return TypeMetaclass('%s%sMap' % (key_klazz.__name__, value_klazz.__name__), (MapContainer,),
      {'KEYTYPE': key_klazz, 'VALUETYPE': value_klazz})
github wickman / pystachio / pystachio / basic.py View on Github external
return TypeCheck.success()
    else:
      # TODO(wickman)  Perhaps we should mark uninterpolated Mustache objects as
      # intrinsically non-stringy, because String will never typecheck false given
      # its input constraints.
      return TypeCheck.failure("%s not a string" % repr(obj._value))

  @classmethod
  def coerce(cls, value):
    ACCEPTED_SOURCE_TYPES = Compatibility.stringy + Compatibility.numeric
    if not isinstance(value, ACCEPTED_SOURCE_TYPES):
      raise cls.CoercionError(value, cls)
    return str(value) if Compatibility.PY3 else unicode(value)


class StringFactory(TypeFactory):
  PROVIDES = 'String'
  @staticmethod
  def create(type_dict, *type_parameters):
    return String


class Integer(SimpleObject):
  @classmethod
  def checker(cls, obj):
    assert isinstance(obj, Integer)
    if isinstance(obj._value, Compatibility.integer):
      return TypeCheck.success()
    else:
      return TypeCheck.failure("%s not an integer" % repr(obj._value))

  @classmethod
github wickman / pystachio / pystachio / container.py View on Github external
import copy
from collections import Iterable, Mapping, Sequence
from inspect import isclass

from .base import Object
from .compatibility import Compatibility
from .naming import Namable, frozendict
from .typing import Type, TypeCheck, TypeFactory, TypeMetaclass


class ListFactory(TypeFactory):
  PROVIDES = 'List'

  @staticmethod
  def create(type_dict, *type_parameters):
    """
      Construct a List containing type 'klazz'.
    """
    assert len(type_parameters) == 1
    klazz = TypeFactory.new(type_dict, *type_parameters[0])
    assert isclass(klazz)
    assert issubclass(klazz, Object)
    return TypeMetaclass('%sList' % klazz.__name__, (ListContainer,), {'TYPE': klazz})


class ListContainer(Object, Namable, Type):
  """
github wickman / pystachio / pystachio / choice.py View on Github external
# Choice types: types that can take one of a group of selected types.


from .base import Object
from .compatibility import Compatibility
from .typing import Type, TypeCheck, TypeFactory, TypeMetaclass


class ChoiceFactory(TypeFactory):
  """A Pystachio type representing a value which can be one of several
  different types.
  For example, a field which could be either an integer, or an integer
  expression (where IntegerExpression is a struct type) could be written
  Choice("IntOrExpr", (Integer, IntegerExpression))
  """
  PROVIDES = 'Choice'

  @staticmethod
  def create(type_dict, *type_parameters):
    """
    type_parameters should be:
      (name, (alternative1, alternative2, ...))
    where name is a string, and the alternatives are all valid serialized
    types.
    """
github wickman / pystachio / pystachio / basic.py View on Github external
def coerce(cls, value):
    if not isinstance(value, Compatibility.stringy) or value not in cls.VALUES:
      raise cls.CoercionError(value, cls, '%s is not one of %s' % (
        value, ', '.join(cls.VALUES)))
    return str(value) if Compatibility.PY3 else unicode(value)

  @classmethod
  def type_factory(cls):
    return 'Enum'

  @classmethod
  def type_parameters(cls):
    return (cls.__name__, cls.VALUES)


class EnumFactory(TypeFactory):
  PROVIDES = 'Enum'

  @staticmethod
  def create(type_dict, *type_parameters):
    """
      EnumFactory.create(*type_parameters) expects:
        enumeration name, (enumeration values)
    """
    name, values = type_parameters
    assert isinstance(values, (list, tuple))
    for value in values:
      assert isinstance(value, Compatibility.stringy)
    return TypeMetaclass(str(name), (EnumContainer,), { 'VALUES': values })


def Enum(*stuff):
github wickman / pystachio / pystachio / basic.py View on Github external
if not isinstance(value, ACCEPTED_SOURCE_TYPES):
      raise cls.CoercionError(value, cls)

    if isinstance(value, bool):
      return value
    elif isinstance(value, Compatibility.stringy):
      if value.lower() in ("true", "1"):
        return True
      elif value.lower() in ("false", "0"):
        return False
      else:
        raise cls.CoercionError(value, cls)
    else:
      return bool(value)

class BooleanFactory(TypeFactory):
  PROVIDES = 'Boolean'
  @staticmethod
  def create(type_dict, *type_parameters):
    return Boolean


class EnumContainer(SimpleObject):
  def __init__(self, value):
    stringish = String(value)
    _, refs = stringish.interpolate()
    if not refs and value not in self.VALUES:
      raise ValueError('%s only accepts the following values: %s' % (
          self.__class__.__name__, ', '.join(self.VALUES)))
    super(EnumContainer, self).__init__(value)

  @classmethod
github wickman / pystachio / pystachio / composite.py View on Github external
"""
    Helper to make composite types read succintly.  Wrap a type and make its
    specification required during type-checking of composite types.
  """
  return TypeSignature(cls, required=True)


def Default(cls, default):
  """
    Helper to make composite types read succintly.  Wrap a type and assign it a
    default if it is unspecified in the construction of the composite type.
  """
  return TypeSignature(cls, required=False, default=default)


class StructFactory(TypeFactory):
  PROVIDES = 'Struct'

  @staticmethod
  def create(type_dict, *type_parameters):
    """
      StructFactory.create(*type_parameters) expects:

        class name,
        ((binding requirement1,),
          (binding requirement2, bound_to_scope),
           ...),
        ((attribute_name1, attribute_sig1 (serialized)),
         (attribute_name2, attribute_sig2 ...),
         ...
         (attribute_nameN, ...))
    """