Converts a stored database value to Python.

        :param py_value: <variant>
        :param context: <orb.Context>

        :return: <variant>
558264
def dbRestore(self, db_value, context=None):
        
        if db_value is None:
            return None
        elif isinstance(db_value, (str, unicode)):
            return self.valueFromString(db_value, context=context)
        else:
            return super(AbstractDatetimeColumn, self).dbRestore(db_value, context=context)
1137339
def to_python(self, value):
        """"""
        if value is None or value == '':
            return value
        if isinstance(value, base.Version):
            return value
        if self.coerce:
            return base.Version.coerce(value, partial=self.partial)
        else:
            return base.Version(value, partial=self.partial)
139459
def to_python(self, value):
        """"""
        cache = None
        if value is None:
            return None

        if isinstance(value, DataDescriptor):
            return value
        elif isinstance(value, dict):
            # Allow pre-hydrated data objects.
            cache = value
            try:
                value = cache['__id']
            except KeyError:
                raise ValidationError("dictionary must contain an '__id' element")
        elif not isinstance(value, int):
            raise ValidationError("field must be a DataDescriptor, data object primary key or dict")

        return DataDescriptor(value, self, cache)
383484
def process_value(self, value):
        
        # UID -> SuperModel
        if api.is_uid(value):
            return self.to_super_model(value)
        # Content -> SuperModel
        elif api.is_object(value):
            return self.to_super_model(value)
        # String -> Unicode
        elif isinstance(value, basestring):
            return safe_unicode(value).encode("utf-8")
        # DateTime -> DateTime
        elif isinstance(value, DateTime):
            return value
        # Process list values
        elif isinstance(value, (LazyMap, list, tuple)):
            return map(self.process_value, value)
        # Process dict values
        elif isinstance(value, (dict)):
            return {k: self.process_value(v) for k, v in value.iteritems()}
        # Process function
        elif safe_callable(value):
            return self.process_value(value())
        # Always return the unprocessed value last
        return value
1052236
def python_value(self, dtype, dvalue):
        """"""
        try:
            return CONVERTERS[dtype](dvalue)
        except KeyError:
            if dtype == clips.common.CLIPSType.MULTIFIELD:
                return self.multifield_to_list()
            if dtype == clips.common.CLIPSType.FACT_ADDRESS:
                return clips.facts.new_fact(self._env, lib.to_pointer(dvalue))
            if dtype == clips.common.CLIPSType.INSTANCE_ADDRESS:
                return clips.classes.Instance(self._env, lib.to_pointer(dvalue))

        return None
927512
def to_python(self, value, resource):
        """"""

        if isinstance(value, dict):
            d = {
                self.aliases.get(k, k): self.to_python(v, resource) if isinstance(v, (dict, list)) else v
                for k, v in six.iteritems(value)
            }
            return type(self.class_name, (), d)
        elif isinstance(value, list):
            return [self.to_python(x, resource) if isinstance(x, (dict, list)) else x for x in value]
        else:
            return value
711285
def get_db_prep_save(self, value, connection, prepared=False):
        
        log.debug("get_db_prep_save: {}, {}", value, type(value))
        if not value:
            return ''
            # For underlying (database) string types, e.g. VARCHAR, this
            # function must always return a string type.
            # https://docs.djangoproject.com/en/1.8/howto/custom-model-fields/
        return python_localized_datetime_to_human_iso(value)
523974
def dbStore(self, typ, py_value):
        
        if py_value is not None:
            py_value = projex.text.decoded(py_value)

            if self.cleaned():
                py_value = self.clean(py_value)

            if self.escaped():
                py_value = self.escape(py_value)

            return py_value
        else:
            return py_value
18171
def to_primitive(self, value, context=None):
        

        if context and context.get('epoch_date'):
            epoch = dt(1970, 1, 1)
            value = (value - epoch).total_seconds()
            return int(value)
        elif context and context.get('datetime_date'):
            return value
        else:
            return super(Type, self).to_primitive(value, context)
1236217
def _value_to_python(value):
  """"""

  assert isinstance(value, struct_pb2.Value)
  field = value.WhichOneof('kind')
  if field == 'number_value':
    return value.number_value
  elif field == 'string_value':
    return value.string_value
  elif field == 'bool_value':
    return value.bool_value
  else:
    raise ValueError('Unknown struct_pb2.Value oneof field set: %s' % field)
507476
def value_to_python(self, value):
        
        if not isinstance(value, bytes):
            raise tldap.exceptions.ValidationError("should be bytes")
        if value is None:
            return value
        try:
            return int(value)
        except (TypeError, ValueError):
            raise tldap.exceptions.ValidationError("is invalid integer")
831785
def to_python(value, seen=None):
  
  seen = seen or set()
  if isinstance(value, framework.TupleLike):
    if value.ident in seen:
      raise RecursionException('to_python: infinite recursion while evaluating %r' % value)
    new_seen = seen.union([value.ident])
    return {k: to_python(value[k], seen=new_seen) for k in value.exportable_keys()}
  if isinstance(value, dict):
    return {k: to_python(value[k], seen=seen) for k in value.keys()}
  if isinstance(value, list):
    return [to_python(x, seen=seen) for x in value]
  return value
543023
def _to_python(cls, setting, raw_value):
        

        type_fn = cls.TYPE_FUNCTIONS.get(setting["type"], setting["type"])

        try:
            value = type_fn(raw_value)
        except ValueError:
            # Shouldn't occur, but just a safeguard in case
            # the db value somehow ended up as an invalid type.
            warn("The setting %s should be of type %s, but the value "
                 "retrieved from the database (%s) could not be converted. "
                 "Using the default instead: %s"
                 % (setting["name"], setting["type"].__name__,
                    repr(raw_value), repr(setting["default"])))
            value = setting["default"]

        return value
740397
def transform(self, value, **kwargs):
        
        if value is None:
            return None

        objid = id(value)
        if objid in self.context:
            return '<...>'
        self.context.add(objid)

        try:
            for serializer in self.serializers:
                try:
                    if serializer.can(value):
                        return serializer.serialize(value, **kwargs)
                except Exception as e:
                    logger.exception(e)
                    return text_type(type(value))

            # if all else fails, lets use the repr of the object
            try:
                return repr(value)
            except Exception as e:
                logger.exception(e)
                # It's common case that a model's __unicode__ definition
                # may try to query the database which if it was not
                # cleaned up correctly, would hit a transaction aborted
                # exception
                return text_type(type(value))
        finally:
            self.context.remove(objid)
908516
def to_python(self, value):
        
        if not value:
            return {}
        elif isinstance(value, six.string_types):
            res = loads(value)
            assert isinstance(res, dict)
            return JSONDict(**res)
        else:
            return value
1128963
def dbRestore(self, db_value, context=None):
        
        if isinstance(db_value, (str, unicode)) and db_value.startswith('{'):
            try:
                db_value = projex.text.safe_eval(db_value)
            except StandardError:
                log.exception('Invalid reference found')
                raise orb.errors.OrbError('Invalid reference found.')

        if isinstance(db_value, dict):
            cls = self.referenceModel()
            if not cls:
                raise orb.errors.ModelNotFound(schema=self.reference())
            else:
                load_event = orb.events.LoadEvent(data=db_value)

                # update the expansion information to not propagate to references
                if context:
                    context = context.copy()
                    expand = context.expandtree(cls)
                    sub_expand = expand.pop(self.name(), {})
                    context.expand = context.raw_values['expand'] = sub_expand

                db_value = cls(loadEvent=load_event, context=context)

        return super(ReferenceColumn, self).dbRestore(db_value, context=context)
582366
def _to_python(self, value):
        
        if isinstance(value, (int, float, long, complex)):
            return value

        if isinstance(value, (list, tuple)):
            value = value[0]

        if value == 'true':
            return True
        elif value == 'false':
            return False

        is_string = False

        if IS_PY3:
            if isinstance(value, bytes):
                value = force_unicode(value)

            if isinstance(value, str):
                is_string = True
        else:
            if isinstance(value, str):
                value = force_unicode(value)

            if isinstance(value, basestring):  # NOQA: F821
                is_string = True

        if is_string:
            possible_datetime = DATETIME_REGEX.search(value)

            if possible_datetime:
                date_values = possible_datetime.groupdict()

                for dk, dv in date_values.items():
                    date_values[dk] = int(dv)

                return datetime.datetime(date_values['year'],
                                         date_values['month'],
                                         date_values['day'],
                                         date_values['hour'],
                                         date_values['minute'],
                                         date_values['second'])

        try:
            # This is slightly gross but it's hard to tell otherwise what the
            # string's original type might have been.
            return ast.literal_eval(value)
        except (ValueError, SyntaxError):
            # If it fails, continue on.
            pass

        return value