Take a string and convert it to a value of proper type.


        .. testsetup::

            from proso.coversion import str2type

        .. doctest::

            >>> print(str2type("[1, 2, 3]")
            [1, 2, 3]
422810
def str2type(value):
    
    if not isinstance(value, str):
        return value
    try:
        return json.loads(value)
    except JSONDecodeError:
        return value
1259762
def from_string(string: str):
        

        spec = Spec()
        parse_context = {"current_subpackage": None}
        for line in string.splitlines():
            spec, parse_context = _parse(spec, parse_context, line)
        return spec
1236553
def is_str(string):
    
    if sys.version_info[:2] >= (3, 0):
        return isinstance(string, str)

    return isinstance(string, basestring)
115672
def prepare(value, should_escape):
    

    if value is None:
        return u''
    type_ = type(value)
    if type_ is not strlist:
        if type_ is not str_class:
            if type_ is bool:
                value = u'true' if value else u'false'
            else:
                value = str_class(value)
        if should_escape:
            value = escape(value)
    return value
969633
def backing_type_for(value):
        
        if isinstance(value, str):
            vtype = "S"
        elif isinstance(value, bytes):
            vtype = "B"
        # NOTE: numbers.Number check must come **AFTER** bool check since isinstance(True, numbers.Number)
        elif isinstance(value, bool):
            vtype = "BOOL"
        elif isinstance(value, numbers.Number):
            vtype = "N"
        elif isinstance(value, dict):
            vtype = "M"
        elif isinstance(value, list):
            vtype = "L"
        elif isinstance(value, set):
            if not value:
                vtype = "SS"  # doesn't matter, Set(x) should dump an empty set the same for all x
            else:
                inner = next(iter(value))
                if isinstance(inner, str):
                    vtype = "SS"
                elif isinstance(inner, bytes):
                    vtype = "BS"
                elif isinstance(inner, numbers.Number):
                    vtype = "NS"
                else:
                    raise ValueError(f"Unknown set type for inner value {inner!r}")
        else:
            raise ValueError(f"Can't dump unexpected type {type(value)!r} for value {value!r}")
        return vtype
486475
def convert(self, string, preprocess = None):
        
        string = unicode(preprocess(string) if preprocess else string, encoding="utf-8")
        if self.regex:
            return self.regex.sub(lambda x: self.substitutes[x.group()], string).encode('utf-8')
        else:
            return string
1179424
def convert(values):
    

    dtype = values.dtype

    if is_categorical_dtype(values):
        return values

    elif is_object_dtype(dtype):
        return values.ravel().tolist()

    if needs_i8_conversion(dtype):
        values = values.view('i8')
    v = values.ravel()

    if compressor == 'zlib':
        _check_zlib()

        # return string arrays like they are
        if dtype == np.object_:
            return v.tolist()

        # convert to a bytes array
        v = v.tostring()
        return ExtType(0, zlib.compress(v))

    elif compressor == 'blosc':
        _check_blosc()

        # return string arrays like they are
        if dtype == np.object_:
            return v.tolist()

        # convert to a bytes array
        v = v.tostring()
        return ExtType(0, blosc.compress(v, typesize=dtype.itemsize))

    # ndarray (on original dtype)
    return ExtType(0, v.tostring())
169841
def str2int(self, str_value):
    """"""
    str_value = tf.compat.as_text(str_value)
    if self._str2int:
      return self._str2int[str_value]

    # No names provided, try to integerize
    failed_parse = False
    try:
      int_value = int(str_value)
    except ValueError:
      failed_parse = True
    if failed_parse or not 0 <= int_value < self._num_classes:
      raise ValueError("Invalid string class label %s" % str_value)
    return int_value
565208
def loads(s, **kwargs):
    
    if not isinstance(s, string_type):
        raise TypeError("Expected s to be a str, got %s" % type(s))

    try:
        fp = unicodeIO(s)
    except TypeError:
        fp = strIO(s)

    return parse(fp, **kwargs)
812796
def from_string(cls, s):
        
        def _qstrip(s):
            return s[1:-1]  # remove assumed quote characters
        tokens = []
        for match in _yy_re.finditer(s):
            d = match.groupdict()
            lnk, pos = None, []
            if d['lnkfrom'] is not None:
                lnk = Lnk.charspan(d['lnkfrom'], d['lnkto'])
            if d['pos'] is not None:
                ps = d['pos'].strip().split()
                pos = list(zip(map(_qstrip, ps[::2]), map(float, ps[1::2])))
            tokens.append(
                YyToken(
                    int(d['id']),
                    int(d['start']),
                    int(d['end']),
                    lnk,
                    list(map(int, d['paths'].strip().split())),
                    _qstrip(d['form']),
                    None if d['surface'] is None else _qstrip(d['surface']),
                    int(d['ipos']),
                    list(map(_qstrip, d['lrules'].strip().split())),
                    pos
                )
            )
        return cls(tokens)
900188
function str2num(type) {
  switch (String(type)) {
    case 'byte':
      return types.BYTE;
    case 'char':
      return types.CHAR;
    case 'short':
      return types.SHORT;
    case 'int':
      return types.INT;
    case 'float':
      return types.FLOAT;
    case 'double':
      return types.DOUBLE;
      /* istanbul ignore next */
    default:
      return -1;
  }
}
810701
def to_bool(value):
    
    cases = {
        '0': False,
        'false': False,
        'no': False,

        '1': True,
        'true': True,
        'yes': True,
    }
    value = value.lower() if isinstance(value, basestring) else value
    return cases.get(value, bool(value))
714160
def fmtstr(string, *args, **kwargs):
    # type: (Union[Text, bytes, FmtStr], *Any, **Any) -> FmtStr
    
    atts = parse_args(args, kwargs)
    if isinstance(string, FmtStr):
        pass
    elif isinstance(string, (bytes, unicode)):
        string = FmtStr.from_str(string)
    else:
        raise ValueError("Bad Args: %r (of type %s), %r, %r" % (string, type(string), args, kwargs))
    return string.copy_with_new_atts(**atts)
954409
def str_to_bool(val):
    

    if isinstance(val, bool):
        return val
    elif val.lower() == 'true':
        return True
    elif val.lower() == 'false':
        return False
    else:
        raise ValueError
399390
def from_string(value):
        
        if value == None or len(value) == 0:
            return None
                
        tokens = value.split(",")
        if len(tokens) == 1:
            return TypeDescriptor(tokens[0].strip(), None)
        elif len(tokens) == 2:
            return TypeDescriptor(tokens[0].strip(), tokens[1].strip())
        else:
            raise ConfigException(
                None, "BAD_DESCRIPTOR", "Type descriptor " + value + " is in wrong format"
            ).with_details("descriptor", value)
400341
def str_val(val):
    
    str_val = val
    if val is None:
        str_val = "NA"
    elif type(val) == float:
        str_val = '%0.2f' % val
    else:
        str_val = str(val)
    return str_val
719591
def dialectfromstring(s):
    
    try:
        AST = compiler.parse(s)
    except SyntaxError:
        return
    else:
        try:
            if (len(AST.getChildren()) > 1):
                ST = AST.getChildren()[1]
                if isinstance(ST, Stmt):
                    if isinstance(ST.getChildren()[0], Discard):
                        d = ST.getChildren()[0].asList()[0]
        except (TypeError,AttributeError):
            pass
        else:
            if (isinstance(d,Dict) and (len(d.items) > 0)):
                if all([isctype(i[0], str) for i in d.items]):
                    testd = csv.Sniffer().sniff('a,b,c')
                    if all([n.value in dir(testd) and 
                        isctype(v, type(getattr(testd, n.value))) for (n,v) in 
                                                                      d.items]):
                        D = eval(s)
                        for n in D.keys():
                            setattr(testd, n, D[n])
                        return testd