Example #1
0
def parse_locals_keylist(locals_, key_list, strlist_=None, prefix=''):
    """ For each key in keylist, puts its value in locals into a stringlist """
    #from utool.util_str import get_callable_name
    from utool.util_str import get_callable_name
    if strlist_ is None:
        strlist_ = []

    for key in key_list:
        try:
            if key is None:
                strlist_.append('')
            elif isinstance(key, tuple):
                # Given a tuple of information
                tup = key
                func, key_ = tup
                val = get_varval_from_locals(key_, locals_)
                funcvalstr = str(func(val))
                strlist_.append('%s %s(%s) = %s' % (prefix, get_callable_name(func), key_, funcvalstr))
            elif isinstance(key, six.string_types):
                # Try to infer print from variable name
                val = get_varval_from_locals(key, locals_)
                valstr = util_str.truncate_str(repr(val), maxlen=200)
                strlist_.append('%s %s = %s' % (prefix, key, valstr))
            else:
                # Try to infer print from variable value
                val = key
                typestr = repr(type(val))
                namestr = get_varname_from_locals(val, locals_)
                valstr = util_str.truncate_str(repr(val), maxlen=200)
                strlist_.append('%s %s %s = %s' % (prefix, typestr, namestr, valstr))
        except AssertionError as ex:
            strlist_.append(str(ex))
    return strlist_
Example #2
0
 def wrp_onexceptreport(*args, **kwargs):
     try:
         #import utool
         #if utool.DEBUG:
         #    print('[IN EXCPRPT] args=%r' % (args,))
         #    print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
         return func(*args, **kwargs)
     except Exception as ex:
         from utool import util_str
         arg_strs = ', '.join([repr(util_str.truncate_str(str(arg))) for arg in args])
         kwarg_strs = ', '.join([util_str.truncate_str('%s=%r' % (key, val)) for key, val in six.iteritems(kwargs)])
         msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
         msg += ' * len(args) = %r\n' % len(args)
         msg += ' * len(kwargs) = %r\n' % len(kwargs)
         util_dbg.printex(ex, msg, pad_stdout=True)
         raise
Example #3
0
def assert_inbounds(num, low, high, msg='', eq=False, verbose=not util_arg.QUIET):
    r"""
    Args:
        num (scalar):
        low (scalar):
        high (scalar):
        msg (str):
    """
    from utool import util_str
    if util_arg.NO_ASSERTS:
        return
    passed = util_alg.inbounds(num, low, high, eq=eq)
    if isinstance(passed, np.ndarray):
        passflag = np.all(passed)
    else:
        passflag = passed
    if not passflag:
        failednum = num.compress(~passed) if isinstance(num, np.ndarray) else num
        failedlow = low.compress(~passed) if isinstance(low, np.ndarray) else low
        failedhigh = high.compress(~passed) if isinstance(high, np.ndarray) else high
        msg_ = 'num=%r is out of bounds=(%r, %r)' % (failednum, failedlow, failedhigh)
        raise AssertionError(msg_ + '\n' + msg)
    else:
        if verbose:
            op = '<=' if eq else '<'
            fmtstr = 'Passed assert_inbounds: {low} {op} {num} {op} {high}'
            print(fmtstr.format(low=low, op=op, num=util_str.truncate_str(str(num)), high=high))
Example #4
0
 def wrp_onexceptreport(*args, **kwargs):
     try:
         #import utool
         #if utool.DEBUG:
         #    print('[IN EXCPRPT] args=%r' % (args,))
         #    print('[IN EXCPRPT] kwargs=%r' % (kwargs,))
         return func(*args, **kwargs)
     except Exception as ex:
         from utool import util_str
         print('ERROR occured! Reporting input to function')
         if keys is not None:
             from utool import util_inspect
             from utool import util_list
             from utool import util_dict
             argspec = util_inspect.get_func_argspec(func)
             in_kwargs_flags = [key in kwargs for key in keys]
             kwarg_keys = util_list.compress(keys, in_kwargs_flags)
             kwarg_vals = [kwargs.get(key) for key in kwarg_keys]
             flags = util_list.not_list(in_kwargs_flags)
             arg_keys = util_list.compress(keys, flags)
             arg_idxs = [argspec.args.index(key) for key in arg_keys]
             num_nodefault = len(argspec.args) - len(argspec.defaults)
             default_vals = (([None] * (num_nodefault)) +
                             list(argspec.defaults))
             args_ = list(args) + default_vals[len(args) + 1:]
             arg_vals = util_list.take(args_, arg_idxs)
             requested_dict = dict(util_list.flatten(
                 [zip(kwarg_keys, kwarg_vals), zip(arg_keys, arg_vals)]))
             print('input dict = ' + util_str.repr4(
                 util_dict.dict_subset(requested_dict, keys)))
             # (print out specific keys only)
             pass
         arg_strs = ', '.join([repr(util_str.truncate_str(str(arg)))
                               for arg in args])
         kwarg_strs = ', '.join([
             util_str.truncate_str('%s=%r' % (key, val))
             for key, val in six.iteritems(kwargs)])
         msg = ('\nERROR: funcname=%r,\n * args=%s,\n * kwargs=%r\n' % (
             meta_util_six.get_funcname(func), arg_strs, kwarg_strs))
         msg += ' * len(args) = %r\n' % len(args)
         msg += ' * len(kwargs) = %r\n' % len(kwargs)
         util_dbg.printex(ex, msg, pad_stdout=True)
         raise
Example #5
0
 def get_printable(self,
                   type_bit=True,
                   print_exclude_aug=[],
                   val_bit=True,
                   max_valstr=MAX_VALSTR,
                   justlength=False):
     from utool.util_dev import printableVal, printableType
     from utool.util_str import truncate_str
     body = ''
     attri_list = []
     exclude_key_list = list(
         self._printable_exclude) + list(print_exclude_aug)
     for (key, val) in six.iteritems(self.__dict__):
         try:
             if key in exclude_key_list:
                 continue
             namestr = str(key)
             typestr = printableType(val, name=key, parent=self)
             if not val_bit:
                 attri_list.append((typestr, namestr, '<ommited>'))
                 continue
             valstr = printableVal(val,
                                   type_bit=type_bit,
                                   justlength=justlength)
             valstr = truncate_str(valstr,
                                   maxlen=max_valstr,
                                   truncmsg=' \n ~~~ \n ')
             #if len(valstr) > max_valstr and max_valstr > 0:
             #    pos1 =  max_valstr // 2
             #    pos2 = -max_valstr // 2
             #    valstr = valstr[0:pos1] + ' \n ~~~ \n ' + valstr[pos2: - 1]
             attri_list.append((typestr, namestr, valstr))
         except Exception as ex:
             print('[printable] ERROR %r' % ex)
             print('[printable] ERROR key = %r' % key)
             print('[printable] ERROR val = %r' % val)
             try:
                 print('[printable] ERROR valstr = %r' % valstr)
             except Exception:
                 pass
             raise
     attri_list.sort()
     for (typestr, namestr, valstr) in attri_list:
         entrytail = '\n' if valstr.count('\n') <= 1 else '\n\n'
         typestr2 = typestr + ' ' if type_bit else ''
         body += typestr2 + namestr + ' = ' + valstr + entrytail
     return body
Example #6
0
 def get_printable(self,
                   type_bit=True,
                   print_exclude_aug=[],
                   val_bit=True,
                   max_valstr=MAX_VALSTR,
                   justlength=False):
     from utool.util_dev import printableVal, printableType
     from utool.util_str import truncate_str
     body = ''
     attri_list = []
     exclude_key_list = list(self._printable_exclude) + list(print_exclude_aug)
     for (key, val) in six.iteritems(self.__dict__):
         try:
             if key in exclude_key_list:
                 continue
             namestr = str(key)
             typestr = printableType(val, name=key, parent=self)
             if not val_bit:
                 attri_list.append((typestr, namestr, '<ommited>'))
                 continue
             valstr = printableVal(val, type_bit=type_bit, justlength=justlength)
             valstr = truncate_str(valstr, maxlen=max_valstr, truncmsg=' \n ~~~ \n ')
             #if len(valstr) > max_valstr and max_valstr > 0:
             #    pos1 =  max_valstr // 2
             #    pos2 = -max_valstr // 2
             #    valstr = valstr[0:pos1] + ' \n ~~~ \n ' + valstr[pos2: - 1]
             attri_list.append((typestr, namestr, valstr))
         except Exception as ex:
             print('[printable] ERROR %r' % ex)
             print('[printable] ERROR key = %r' % key)
             print('[printable] ERROR val = %r' % val)
             try:
                 print('[printable] ERROR valstr = %r' % valstr)
             except Exception:
                 pass
             raise
     attri_list.sort()
     for (typestr, namestr, valstr) in attri_list:
         entrytail = '\n' if valstr.count('\n') <= 1 else '\n\n'
         typestr2 = typestr + ' ' if type_bit else ''
         body += typestr2 + namestr + ' = ' + valstr + entrytail
     return body
Example #7
0
 def __explore_module(module, indent, seen, depth, maxdepth, nonmodules):
     valid_children = []
     ret = u''
     modname = str(module.__name__)
     #modname = repr(module)
     for child, aname in __childiter(module):
         try:
             childtype = type(child)
             if not isinstance(childtype, types.ModuleType):
                 if nonmodules:
                     #print_(depth)
                     fullstr = indent + '    ' + str(aname) + ' = ' + repr(child)
                     truncstr = util_str.truncate_str(fullstr) + '\n'
                     ret +=  truncstr
                 continue
             childname = str(child.__name__)
             if seen is not None:
                 if childname in seen:
                     continue
                 elif maxdepth is None:
                     seen.add(childname)
             if childname.find('_') == 0:
                 continue
             valid_children.append(child)
         except Exception as ex:
             print(repr(ex))
             pass
     # Print
     # print_(depth)
     ret += indent + modname + '\n'
     # Recurse
     if maxdepth is not None and depth >= maxdepth:
         return ret
     ret += ''.join([__explore_module(child,
                                      indent + '    ',
                                      seen, depth + 1,
                                      maxdepth,
                                      nonmodules)
                    for child in iter(valid_children)])
     return ret
Example #8
0
def assert_inbounds(num,
                    low,
                    high,
                    msg='',
                    eq=False,
                    verbose=not util_arg.QUIET):
    r"""
    Args:
        num (scalar):
        low (scalar):
        high (scalar):
        msg (str):
    """
    from utool import util_str
    if util_arg.NO_ASSERTS:
        return
    passed = util_alg.inbounds(num, low, high, eq=eq)
    if isinstance(passed, np.ndarray):
        passflag = np.all(passed)
    else:
        passflag = passed
    if not passflag:
        failednum = num.compress(~passed) if isinstance(num,
                                                        np.ndarray) else num
        failedlow = low.compress(~passed) if isinstance(low,
                                                        np.ndarray) else low
        failedhigh = high.compress(~passed) if isinstance(high,
                                                          np.ndarray) else high
        msg_ = 'num=%r is out of bounds=(%r, %r)' % (failednum, failedlow,
                                                     failedhigh)
        raise AssertionError(msg_ + '\n' + msg)
    else:
        if verbose:
            op = '<=' if eq else '<'
            fmtstr = 'Passed assert_inbounds: {low} {op} {num} {op} {high}'
            print(
                fmtstr.format(low=low,
                              op=op,
                              num=util_str.truncate_str(str(num)),
                              high=high))
Example #9
0
 def __explore_module(module, indent, seen, depth, maxdepth, nonmodules):
     valid_children = []
     ret = u''
     modname = six.text_type(module.__name__)
     #modname = repr(module)
     for child, aname in __childiter(module):
         try:
             childtype = type(child)
             if not isinstance(childtype, types.ModuleType):
                 if nonmodules:
                     fullstr = indent + '    ' + six.text_type(aname) + ' = ' + repr(child)
                     truncstr = util_str.truncate_str(fullstr) + '\n'
                     ret +=  truncstr
                 continue
             childname = six.text_type(child.__name__)
             if seen is not None:
                 if childname in seen:
                     continue
                 elif maxdepth is None:
                     seen.add(childname)
             if childname.find('_') == 0:
                 continue
             valid_children.append(child)
         except Exception as ex:
             print(repr(ex))
             pass
     # Print
     ret += indent + modname + '\n'
     # Recurse
     if maxdepth is not None and depth >= maxdepth:
         return ret
     ret += ''.join([__explore_module(child,
                                      indent + '    ',
                                      seen, depth + 1,
                                      maxdepth,
                                      nonmodules)
                    for child in iter(valid_children)])
     return ret
Example #10
0
def parse_locals_keylist(locals_, key_list, strlist_=None, prefix=''):
    """ For each key in keylist, puts its value in locals into a stringlist

    Args:
        locals_ (?):
        key_list (list):
        strlist_ (list): (default = None)
        prefix (unicode): (default = u'')

    Returns:
        list: strlist_

    CommandLine:
        python -m utool.util_dbg --exec-parse_locals_keylist

    Example:
        >>> # ENABLE_DOCTEST
        >>> from utool.util_dbg import *  # NOQA
        >>> import utool as ut
        >>> locals_ = {'foo': [1, 2, 3], 'bar': 'spam', 'eggs': 4, 'num': 5}
        >>> key_list = [(len, 'foo'), 'bar.lower.__name__', 'eggs', 'num', 'other']
        >>> strlist_ = None
        >>> prefix = u''
        >>> strlist_ = parse_locals_keylist(locals_, key_list, strlist_, prefix)
        >>> result = ('strlist_ = %s' % (ut.repr2(strlist_, nl=True),))
        >>> print(result)
        strlist_ = [
            ' len(foo) = 3',
            " bar.lower.__name__ = 'lower'",
            ' eggs = 4',
            ' num = 5',
            ' other = NameError (this likely due to a misformatted printex and is not related to the exception)',
        ]
    """
    from utool import util_str
    if strlist_ is None:
        strlist_ = []

    for key in key_list:
        try:
            if key is None:
                strlist_.append('')
            elif isinstance(key, tuple):
                # Given a tuple of information
                tup = key
                func, key_ = tup
                val = get_varval_from_locals(key_, locals_)
                funcvalstr = six.text_type(func(val))
                callname = util_str.get_callable_name(func)
                strlist_.append('%s %s(%s) = %s' % (prefix, callname, key_, funcvalstr))
            elif isinstance(key, six.string_types):
                # Try to infer print from variable name
                val = get_varval_from_locals(key, locals_)
                #valstr = util_str.truncate_str(repr(val), maxlen=200)
                valstr = util_str.truncate_str(util_str.repr2(val), maxlen=200)
                strlist_.append('%s %s = %s' % (prefix, key, valstr))
            else:
                # Try to infer print from variable value
                val = key
                typestr = repr(type(val))
                namestr = get_varname_from_locals(val, locals_)
                #valstr = util_str.truncate_str(repr(val), maxlen=200)
                valstr = util_str.truncate_str(util_str.repr2(val), maxlen=200)
                strlist_.append('%s %s %s = %s' % (prefix, typestr, namestr, valstr))
        except AssertionError as ex:
            strlist_.append(prefix + ' ' + six.text_type(ex) + ' (this likely due to a misformatted printex and is not related to the exception)')
    return strlist_