Python builtins.bool() Examples

The following are 30 code examples of builtins.bool(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module builtins , or try the search function .
Example #1
Source File: _iotools.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == 'TRUE':
        return True
    elif value == 'FALSE':
        return False
    else:
        raise ValueError("Invalid boolean") 
Example #2
Source File: numerictypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def issubdtype(arg1, arg2):
    """
    Returns True if first argument is a typecode lower/equal in type hierarchy.

    Parameters
    ----------
    arg1, arg2 : dtype_like
        dtype or string representing a typecode.

    Returns
    -------
    out : bool

    See Also
    --------
    issubsctype, issubclass_
    numpy.core.numerictypes : Overview of numpy type hierarchy.

    Examples
    --------
    >>> np.issubdtype('S1', str)
    True
    >>> np.issubdtype(np.float64, np.float32)
    False

    """
    if issubclass_(arg2, generic):
        return issubclass(dtype(arg1).type, arg2)
    mro = dtype(arg2).type.mro()
    if len(mro) > 1:
        val = mro[1]
    else:
        val = mro[0]
    return issubclass(dtype(arg1).type, val)


# This dictionary allows look up based on any alias for an array data-type 
Example #3
Source File: _iotools.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == 'TRUE':
        return True
    elif value == 'FALSE':
        return False
    else:
        raise ValueError("Invalid boolean") 
Example #4
Source File: numerictypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError is one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, np.int)
    True
    >>> np.issubclass_(np.int32, np.float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #5
Source File: numerictypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _add_aliases():
    for a in typeinfo.keys():
        name = english_lower(a)
        if not isinstance(typeinfo[a], tuple):
            continue
        typeobj = typeinfo[a][-1]
        # insert bit-width version for this class (if relevant)
        base, bit, char = bitname(typeobj)
        if base[-3:] == 'int' or char[0] in 'ui': continue
        if base != '':
            myname = "%s%d" % (base, bit)
            if (name != 'longdouble' and name != 'clongdouble') or \
                   myname not in allTypes.keys():
                allTypes[myname] = typeobj
                sctypeDict[myname] = typeobj
                if base == 'complex':
                    na_name = '%s%d' % (english_capitalize(base), bit//2)
                elif base == 'bool':
                    na_name = english_capitalize(base)
                    sctypeDict[na_name] = typeobj
                else:
                    na_name = "%s%d" % (english_capitalize(base), bit)
                    sctypeDict[na_name] = typeobj
                sctypeNA[na_name] = typeobj
                sctypeDict[na_name] = typeobj
                sctypeNA[typeobj] = na_name
                sctypeNA[typeinfo[a][0]] = na_name
        if char != '':
            sctypeDict[char] = typeobj
            sctypeNA[char] = na_name 
Example #6
Source File: _iotools.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == asbytes('TRUE'):
        return True
    elif value == asbytes('FALSE'):
        return False
    else:
        raise ValueError("Invalid boolean") 
Example #7
Source File: numerictypes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def issubsctype(arg1, arg2):
    """
    Determine if the first argument is a subclass of the second argument.

    Parameters
    ----------
    arg1, arg2 : dtype or dtype specifier
        Data-types.

    Returns
    -------
    out : bool
        The result.

    See Also
    --------
    issctype, issubdtype,obj2sctype

    Examples
    --------
    >>> np.issubsctype('S8', str)
    True
    >>> np.issubsctype(np.array([1]), np.int)
    True
    >>> np.issubsctype(np.array([1]), np.float)
    False

    """
    return issubclass(obj2sctype(arg1), obj2sctype(arg2)) 
Example #8
Source File: numerictypes.py    From pySINDy with MIT License 5 votes vote down vote up
def _add_aliases():
    for type_name, info in typeinfo.items():
        if isinstance(info, type):
            continue
        name = english_lower(type_name)

        # insert bit-width version for this class (if relevant)
        base, bit, char = bitname(info.type)
        if base[-3:] == 'int' or char[0] in 'ui':
            continue
        if base != '':
            myname = "%s%d" % (base, bit)
            if (name not in ('longdouble', 'clongdouble') or
                   myname not in allTypes):
                base_capitalize = english_capitalize(base)
                if base == 'complex':
                    na_name = '%s%d' % (base_capitalize, bit//2)
                elif base == 'bool':
                    na_name = base_capitalize
                else:
                    na_name = "%s%d" % (base_capitalize, bit)

                allTypes[myname] = info.type

                # add mapping for both the bit name and the numarray name
                sctypeDict[myname] = info.type
                sctypeDict[na_name] = info.type

                # add forward, reverse, and string mapping to numarray
                sctypeNA[na_name] = info.type
                sctypeNA[info.type] = na_name
                sctypeNA[info.char] = na_name
        if char != '':
            sctypeDict[char] = info.type
            sctypeNA[char] = na_name 
Example #9
Source File: numerictypes.py    From pySINDy with MIT License 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError if one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, int)
    True
    >>> np.issubclass_(np.int32, float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #10
Source File: numerictypes.py    From pySINDy with MIT License 5 votes vote down vote up
def issubsctype(arg1, arg2):
    """
    Determine if the first argument is a subclass of the second argument.

    Parameters
    ----------
    arg1, arg2 : dtype or dtype specifier
        Data-types.

    Returns
    -------
    out : bool
        The result.

    See Also
    --------
    issctype, issubdtype,obj2sctype

    Examples
    --------
    >>> np.issubsctype('S8', str)
    True
    >>> np.issubsctype(np.array([1]), int)
    True
    >>> np.issubsctype(np.array([1]), float)
    False

    """
    return issubclass(obj2sctype(arg1), obj2sctype(arg2)) 
Example #11
Source File: _iotools.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def flatten_dtype(ndtype, flatten_base=False):
    """
    Unpack a structured data-type by collapsing nested fields and/or fields
    with a shape.

    Note that the field names are lost.

    Parameters
    ----------
    ndtype : dtype
        The datatype to collapse
    flatten_base : bool, optional
       If True, transform a field with a shape into several fields. Default is
       False.

    Examples
    --------
    >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
    ...                ('block', int, (2, 3))])
    >>> np.lib._iotools.flatten_dtype(dt)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')]
    >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'),
     dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'),
     dtype('int32')]

    """
    names = ndtype.names
    if names is None:
        if flatten_base:
            return [ndtype.base] * int(np.prod(ndtype.shape))
        return [ndtype.base]
    else:
        types = []
        for field in names:
            info = ndtype.fields[field]
            flat_dt = flatten_dtype(info[0], flatten_base)
            types.extend(flat_dt)
        return types 
Example #12
Source File: _iotools.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == b'TRUE':
        return True
    elif value == b'FALSE':
        return False
    else:
        raise ValueError("Invalid boolean") 
Example #13
Source File: numerictypes.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def _add_aliases():
    for a in typeinfo.keys():
        name = english_lower(a)
        if not isinstance(typeinfo[a], tuple):
            continue
        typeobj = typeinfo[a][-1]
        # insert bit-width version for this class (if relevant)
        base, bit, char = bitname(typeobj)
        if base[-3:] == 'int' or char[0] in 'ui':
            continue
        if base != '':
            myname = "%s%d" % (base, bit)
            if ((name != 'longdouble' and name != 'clongdouble') or
                   myname not in allTypes.keys()):
                allTypes[myname] = typeobj
                sctypeDict[myname] = typeobj
                if base == 'complex':
                    na_name = '%s%d' % (english_capitalize(base), bit//2)
                elif base == 'bool':
                    na_name = english_capitalize(base)
                    sctypeDict[na_name] = typeobj
                else:
                    na_name = "%s%d" % (english_capitalize(base), bit)
                    sctypeDict[na_name] = typeobj
                sctypeNA[na_name] = typeobj
                sctypeDict[na_name] = typeobj
                sctypeNA[typeobj] = na_name
                sctypeNA[typeinfo[a][0]] = na_name
        if char != '':
            sctypeDict[char] = typeobj
            sctypeNA[char] = na_name 
Example #14
Source File: numerictypes.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError if one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, np.int)
    True
    >>> np.issubclass_(np.int32, np.float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #15
Source File: _iotools.py    From pySINDy with MIT License 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == 'TRUE':
        return True
    elif value == 'FALSE':
        return False
    else:
        raise ValueError("Invalid boolean") 
Example #16
Source File: numerictypes.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError if one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, int)
    True
    >>> np.issubclass_(np.int32, float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #17
Source File: _iotools.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 5 votes vote down vote up
def flatten_dtype(ndtype, flatten_base=False):
    """
    Unpack a structured data-type by collapsing nested fields and/or fields
    with a shape.

    Note that the field names are lost.

    Parameters
    ----------
    ndtype : dtype
        The datatype to collapse
    flatten_base : bool, optional
       If True, transform a field with a shape into several fields. Default is
       False.

    Examples
    --------
    >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
    ...                ('block', int, (2, 3))])
    >>> np.lib._iotools.flatten_dtype(dt)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')]
    >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'),
     dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'),
     dtype('int32')]

    """
    names = ndtype.names
    if names is None:
        if flatten_base:
            return [ndtype.base] * int(np.prod(ndtype.shape))
        return [ndtype.base]
    else:
        types = []
        for field in names:
            info = ndtype.fields[field]
            flat_dt = flatten_dtype(info[0], flatten_base)
            types.extend(flat_dt)
        return types 
Example #18
Source File: numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def issubsctype(arg1, arg2):
    """
    Determine if the first argument is a subclass of the second argument.

    Parameters
    ----------
    arg1, arg2 : dtype or dtype specifier
        Data-types.

    Returns
    -------
    out : bool
        The result.

    See Also
    --------
    issctype, issubdtype,obj2sctype

    Examples
    --------
    >>> np.issubsctype('S8', str)
    True
    >>> np.issubsctype(np.array([1]), int)
    True
    >>> np.issubsctype(np.array([1]), float)
    False

    """
    return issubclass(obj2sctype(arg1), obj2sctype(arg2)) 
Example #19
Source File: numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError if one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, int)
    True
    >>> np.issubclass_(np.int32, float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #20
Source File: numerictypes.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def _add_aliases():
    for type_name, info in typeinfo.items():
        if isinstance(info, type):
            continue
        name = english_lower(type_name)

        # insert bit-width version for this class (if relevant)
        base, bit, char = bitname(info.type)
        if base[-3:] == 'int' or char[0] in 'ui':
            continue
        if base != '':
            myname = "%s%d" % (base, bit)
            if (name not in ('longdouble', 'clongdouble') or
                   myname not in allTypes):
                base_capitalize = english_capitalize(base)
                if base == 'complex':
                    na_name = '%s%d' % (base_capitalize, bit//2)
                elif base == 'bool':
                    na_name = base_capitalize
                else:
                    na_name = "%s%d" % (base_capitalize, bit)

                allTypes[myname] = info.type

                # add mapping for both the bit name and the numarray name
                sctypeDict[myname] = info.type
                sctypeDict[na_name] = info.type

                # add forward, reverse, and string mapping to numarray
                sctypeNA[na_name] = info.type
                sctypeNA[info.type] = na_name
                sctypeNA[info.char] = na_name
        if char != '':
            sctypeDict[char] = info.type
            sctypeNA[char] = na_name 
Example #21
Source File: _iotools.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == 'TRUE':
        return True
    elif value == 'FALSE':
        return False
    else:
        raise ValueError("Invalid boolean") 
Example #22
Source File: _iotools.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def flatten_dtype(ndtype, flatten_base=False):
    """
    Unpack a structured data-type by collapsing nested fields and/or fields
    with a shape.

    Note that the field names are lost.

    Parameters
    ----------
    ndtype : dtype
        The datatype to collapse
    flatten_base : bool, optional
       If True, transform a field with a shape into several fields. Default is
       False.

    Examples
    --------
    >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
    ...                ('block', int, (2, 3))])
    >>> np.lib._iotools.flatten_dtype(dt)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')]
    >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'),
     dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'),
     dtype('int32')]

    """
    names = ndtype.names
    if names is None:
        if flatten_base:
            return [ndtype.base] * int(np.prod(ndtype.shape))
        return [ndtype.base]
    else:
        types = []
        for field in names:
            info = ndtype.fields[field]
            flat_dt = flatten_dtype(info[0], flatten_base)
            types.extend(flat_dt)
        return types 
Example #23
Source File: numerictypes.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError if one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, int)
    True
    >>> np.issubclass_(np.int32, float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #24
Source File: _iotools.py    From recruit with Apache License 2.0 5 votes vote down vote up
def flatten_dtype(ndtype, flatten_base=False):
    """
    Unpack a structured data-type by collapsing nested fields and/or fields
    with a shape.

    Note that the field names are lost.

    Parameters
    ----------
    ndtype : dtype
        The datatype to collapse
    flatten_base : bool, optional
       If True, transform a field with a shape into several fields. Default is
       False.

    Examples
    --------
    >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
    ...                ('block', int, (2, 3))])
    >>> np.lib._iotools.flatten_dtype(dt)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')]
    >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'),
     dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'),
     dtype('int32')]

    """
    names = ndtype.names
    if names is None:
        if flatten_base:
            return [ndtype.base] * int(np.prod(ndtype.shape))
        return [ndtype.base]
    else:
        types = []
        for field in names:
            info = ndtype.fields[field]
            flat_dt = flatten_dtype(info[0], flatten_base)
            types.extend(flat_dt)
        return types 
Example #25
Source File: _iotools.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def flatten_dtype(ndtype, flatten_base=False):
    """
    Unpack a structured data-type by collapsing nested fields and/or fields
    with a shape.

    Note that the field names are lost.

    Parameters
    ----------
    ndtype : dtype
        The datatype to collapse
    flatten_base : bool, optional
       If True, transform a field with a shape into several fields. Default is
       False.

    Examples
    --------
    >>> dt = np.dtype([('name', 'S4'), ('x', float), ('y', float),
    ...                ('block', int, (2, 3))])
    >>> np.lib._iotools.flatten_dtype(dt)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32')]
    >>> np.lib._iotools.flatten_dtype(dt, flatten_base=True)
    [dtype('|S4'), dtype('float64'), dtype('float64'), dtype('int32'),
     dtype('int32'), dtype('int32'), dtype('int32'), dtype('int32'),
     dtype('int32')]

    """
    names = ndtype.names
    if names is None:
        if flatten_base:
            return [ndtype.base] * int(np.prod(ndtype.shape))
        return [ndtype.base]
    else:
        types = []
        for field in names:
            info = ndtype.fields[field]
            flat_dt = flatten_dtype(info[0], flatten_base)
            types.extend(flat_dt)
        return types 
Example #26
Source File: numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def issubdtype(arg1, arg2):
    """
    Returns True if first argument is a typecode lower/equal in type hierarchy.

    Parameters
    ----------
    arg1, arg2 : dtype_like
        dtype or string representing a typecode.

    Returns
    -------
    out : bool

    See Also
    --------
    issubsctype, issubclass_
    numpy.core.numerictypes : Overview of numpy type hierarchy.

    Examples
    --------
    >>> np.issubdtype('S1', str)
    True
    >>> np.issubdtype(np.float64, np.float32)
    False

    """
    if issubclass_(arg2, generic):
        return issubclass(dtype(arg1).type, arg2)
    mro = dtype(arg2).type.mro()
    if len(mro) > 1:
        val = mro[1]
    else:
        val = mro[0]
    return issubclass(dtype(arg1).type, val)


# This dictionary allows look up based on any alias for an array data-type 
Example #27
Source File: numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def issubsctype(arg1, arg2):
    """
    Determine if the first argument is a subclass of the second argument.

    Parameters
    ----------
    arg1, arg2 : dtype or dtype specifier
        Data-types.

    Returns
    -------
    out : bool
        The result.

    See Also
    --------
    issctype, issubdtype,obj2sctype

    Examples
    --------
    >>> np.issubsctype('S8', str)
    True
    >>> np.issubsctype(np.array([1]), np.int)
    True
    >>> np.issubsctype(np.array([1]), np.float)
    False

    """
    return issubclass(obj2sctype(arg1), obj2sctype(arg2)) 
Example #28
Source File: numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def issubclass_(arg1, arg2):
    """
    Determine if a class is a subclass of a second class.

    `issubclass_` is equivalent to the Python built-in ``issubclass``,
    except that it returns False instead of raising a TypeError is one
    of the arguments is not a class.

    Parameters
    ----------
    arg1 : class
        Input class. True is returned if `arg1` is a subclass of `arg2`.
    arg2 : class or tuple of classes.
        Input class. If a tuple of classes, True is returned if `arg1` is a
        subclass of any of the tuple elements.

    Returns
    -------
    out : bool
        Whether `arg1` is a subclass of `arg2` or not.

    See Also
    --------
    issubsctype, issubdtype, issctype

    Examples
    --------
    >>> np.issubclass_(np.int32, np.int)
    True
    >>> np.issubclass_(np.int32, np.float)
    False

    """
    try:
        return issubclass(arg1, arg2)
    except TypeError:
        return False 
Example #29
Source File: numerictypes.py    From Computable with MIT License 5 votes vote down vote up
def _add_aliases():
    for a in typeinfo.keys():
        name = english_lower(a)
        if not isinstance(typeinfo[a], tuple):
            continue
        typeobj = typeinfo[a][-1]
        # insert bit-width version for this class (if relevant)
        base, bit, char = bitname(typeobj)
        if base[-3:] == 'int' or char[0] in 'ui': continue
        if base != '':
            myname = "%s%d" % (base, bit)
            if (name != 'longdouble' and name != 'clongdouble') or \
                   myname not in allTypes.keys():
                allTypes[myname] = typeobj
                sctypeDict[myname] = typeobj
                if base == 'complex':
                    na_name = '%s%d' % (english_capitalize(base), bit//2)
                elif base == 'bool':
                    na_name = english_capitalize(base)
                    sctypeDict[na_name] = typeobj
                else:
                    na_name = "%s%d" % (english_capitalize(base), bit)
                    sctypeDict[na_name] = typeobj
                sctypeNA[na_name] = typeobj
                sctypeDict[na_name] = typeobj
                sctypeNA[typeobj] = na_name
                sctypeNA[typeinfo[a][0]] = na_name
        if char != '':
            sctypeDict[char] = typeobj
            sctypeNA[char] = na_name 
Example #30
Source File: _iotools.py    From Computable with MIT License 5 votes vote down vote up
def str2bool(value):
    """
    Tries to transform a string supposed to represent a boolean to a boolean.

    Parameters
    ----------
    value : str
        The string that is transformed to a boolean.

    Returns
    -------
    boolval : bool
        The boolean representation of `value`.

    Raises
    ------
    ValueError
        If the string is not 'True' or 'False' (case independent)

    Examples
    --------
    >>> np.lib._iotools.str2bool('TRUE')
    True
    >>> np.lib._iotools.str2bool('false')
    False

    """
    value = value.upper()
    if value == asbytes('TRUE'):
        return True
    elif value == asbytes('FALSE'):
        return False
    else:
        raise ValueError("Invalid boolean")