Source

show / show / core.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
"""Debugging print features. """

import inspect, sys, os, re, six
from options import Options, OptionsContext, Transient 
from say import Say, fmt, say
from show.linecacher import *
import linecache, ast, codegen
from mementos import MementoMetaclass, with_metaclass
import textwrap

from options.nulltype import NullType
Private    = NullType('Private')
Impossible = NullType('Impossible')
Ignore     = NullType('Ignore')

_PY3 = sys.version_info[0] > 2

def wrapped_if(value, prefix="", suffix="", transform=None):
    """
    If a string has a value, then transform it (optinally) and add the prefix and
    suffix. Else, return empty string. Handy for formatting operations, where
    one often wants to add decoration iff the value exists.
    """
    
    if not value:
        return ""
    s = transform(str(value)) if transform else str(value)
    return (prefix or "") + s + (suffix or "")

QUOTE_CHARS = ('"', "'", '"""')

class CallArgs(with_metaclass(MementoMetaclass, ast.NodeVisitor)):
    """
    An ``ast.NodeVisitor`` that parses a Python function call and determines its
    arguments from the corresponding AST. Memoized so that parsing and
    traversing the AST is done once and only once; subseqnet requests are
    delivered via cache lookup.
    """

    TARGET_FUNCS = set(['show', 'show.items', 'show.props', 'show.watch'])  # functions we care about

    def __init__(self, filepath, lineno):
        ast.NodeVisitor.__init__(self)
        self.filepath = filepath
        self.lineno   = lineno
        self.source   = None  # placeholder
        self.ast      = None  # placeholder
        self.args     = None  # placeholder
        self.get_ast()
        self.visit(self.ast)
    
    def get_ast(self):
        """
        Find the AST. Easy if single source line contains whole line. May
        need a bit of trial-and-error if over multiple lines.
        """
        src = ""
        for lastlineno in range(self.lineno, self.lineno+10):
            src += getline(self.filepath, lastlineno)
            try:
                srcleft = textwrap.dedent(src)
                self.ast = ast.parse(srcleft)
                self.source = src
                return
            except IndentationError:
                pass
            except SyntaxError:
                pass
        raise RuntimeError('Failed to parse:\n{}\n'.format(src))
        
    def visit_Call(self, node):
        """
        Called for all ``ast.Call`` nodes. Collects source of each argument.
        Note that AST ``starargs`` and ``keywords`` properties are not
        considered. Because ``CallArgs`` parses just one line of source code out
        of its module's context, ``ast.parse`` assumes that arguments are
        normal, not ``*args``. And ``**kwargs`` we can ignore, because those are
        pragmas, not data.
        """
        
        def call_name(n):
            """
            Given an ast.Call node, return the name of the called function, if
            discoverable. Only attempts to decode the common ``func()`` and
            ``object.method()`` cases that we care about for the ``show``
            module. Others return ``None``.
            """
            if isinstance(n.func, ast.Name):
                return n.func.id
            elif isinstance(n.func, ast.Attribute):
                a = n.func
                if isinstance(a.value, ast.Name): 
                    return '.'.join([a.value.id, a.attr])
                else:
                    return None # could be an attribute of a call, but for those, we don't much care
            else:
                raise ValueError("Uh...I'm confused!")
        
        name = call_name(node)
        if name in self.TARGET_FUNCS:
            self.args = [ codegen.to_source(arg) for arg in node.args ]
        else:
            # visit its children
            ast.NodeVisitor.generic_visit(self, node)

# probably cannot make this work from interactive Python
# http://stackoverflow.com/questions/13204161/how-to-access-the-calling-source-line-from-interactive-shell

def cwsv_or_list(data):
    """
    Take a list, a comma-separated values string, or a whitespace-separated values
    string, and return a list.
    """
    if not data:
        return []
    elif isinstance(data, list):
        return data
    elif ',' in data:
        return data.strip().split(',')
    else:
        return data.strip().split()
    
def ellipsis(s, maxlen=232):
    s = str(s)
    if len(s) > maxlen:
        return s[:maxlen-3] + '...'
    else:
        return s

def _afunction(f): pass
function = type(_afunction)
module   = type(sys)
class _XYZ(object):
    def method(self): pass

FUNKY = (function, module, type, type(_XYZ.method), type(len)) # funky => functional infrastructure

class Show(object):
    """Show objects print debug output in a 'name: value' format that
    is convenient for discovering what's going on as a program runs."""
    
    options = Options(
        show_module=False,  # Show the module name in the call location
        where=False,        # show the call location of each call
        sep="  ",           # separate items with two spaces, by default
        retvalue=False,     # return the value printed?
        props=Transient,    # props desired to print (given at call time)
        omit=Transient,     # vars not to print (for show.locals)
        fmtfunc=repr,       # formatting func used to format each value
        show=True,          # show or not
    )

    def __init__(self, **kwargs):
        self.options = Show.options.push(kwargs)
        self.say = Say(retvalue=self.options.retvalue)
        self.opts = None  # per call options, set on each call to reflect transient state
        self._watching = {} # remembers last value of variables for given frames
    
    def call_location(self, caller):
        """
        Create a call location string indicating where a show() was called.
        """
        if isInteractive:
            return "<stdin>:{0}".format(len(history.lines))
        else:
            module_name = ""
            if self.opts.show_module:
                filepath = caller.f_locals.get('__file__', caller.f_globals.get('__file__', 'UNKNOWN'))
                filename = os.path.basename(filepath)
                module_name = re.sub(r'.py', '', filename)
            
            lineno = caller.f_lineno
            co_name = caller.f_code.co_name
            if co_name == '<module>':
                co_name = '__main__'
            func_location = wrapped_if(module_name, ":") + wrapped_if(co_name, "", "()")
            return ':'.join([func_location, str(lineno)])
    
    def value_repr(self, value):
        """
        Return a ``repr()`` string for value that has any brace characters (e.g.
        for ``dict``--and in Python 3, ``set`--literals) doubled so that they
        are not interpreted as format template characters when the composed string
        is eventually output by ``say``.
        """
        return self.say.escape(self.opts.fmtfunc(value))

    def arg_format(self, name, value, caller):
        """
        Format a single argument. Strings returned formatted.
        """
        if name.startswith(QUOTE_CHARS):
            return fmt(value, **{'_callframe': caller})
        else:
            return ': '.join( [ name, self.value_repr(value) ] )

    def arg_format_items(self, name, value, caller):
        """
        Format a single argument to show items of a collection.
        """
        if name.startswith(QUOTE_CHARS):
            ret = fmt(value, **{'_callframe': caller})
            return ret
        else:
            fvalue = self.value_repr(value)
            if isinstance(value, (list, dict, set, six.string_types)):  # weak test
                length = len(value)
                itemname = 'char' if isinstance(value, six.string_types) else 'item'
                s_or_nothing = '' if length == 1 else 's'
                return "{0} ({1} {2}{3}): {4}".format(name, length, itemname, s_or_nothing, fvalue)
            else:
                return "{0}: {1}".format(name, fvalue)

    def arg_format_props(self, name, value, caller, ignore_double=True, ignore_funky=True):
        """
        Format a single argument to show properties.
        """
        if name.startswith(QUOTE_CHARS):
            ret = fmt(value, **{'_callframe': caller})
            return ret
        else:
            try:
                props = self.opts.props
                if props and isinstance(props, str):
                    proplist = props.split(',') if ',' in props else props.split()
                else:
                    try:
                        propkeys = list(value.__dict__.keys())
                    except AttributeError:  # no __dict__ => __slots__ object
                        t = type(value)
                        try:
                            propkeys = list(t.__dict__.keys())
                        except AttributeError:
                            try:
                                propkeys = list(t.__slots__)
                            except AttributeError:
                                propkeys = list(dir(value))
                    
                    # Might add option to show attributes not in self.__dict__ but
                    # inherited from the class (as ``dir`` does always)
                    
                    try:
                        cdict = value.__class__.__dict__
                        realproperties = [ k for k in cdict.keys() if isinstance(cdict[k], property) ]
                        propkeys.extend(realproperties)
                    except AttributeError:
                        pass
            
                    if ignore_double:
                        propkeys = [ p for p in propkeys if not p.startswith('__') ]
                    if ignore_funky:
                        propkeys = [ p for p in propkeys if not isinstance(getattr(value, p), FUNKY) ]
                    if self.opts.omit:
                        omitlist = cwsv_or_list(self.opts.omit) 
                        propkeys = [ p for p in propkeys if not p in omitlist ]

                    proplist = sorted(propkeys, key=lambda x: x.replace('_','~'))
                #propvals = [ "{0}={1}".format(p, self.value_repr(getattr(value, p))) for p in proplist ]
                #return "{0}: {1}".format(name, ' '.join(propvals))
                propvals = [ "    {0}={1}".format(p, ellipsis(self.value_repr(getattr(value, p)))) for p in proplist ]
                return "{0}:\n{1}".format(name, '\n'.join(propvals))
            except Exception:
                return "{0}: {1}".format(name, self.value_repr(value))
       
    def get_arg_tuples(self, caller, values):
        """
        Return a list of argument name, value tuples with the given values.
        """
        filename, lineno = frame_to_source_info(caller)
        argnames = CallArgs(filename, lineno).args
        argtuples = list(zip(list(argnames), list(values)))
        return argtuples
    
    def settings(self, **kwargs):
        """
        Open a context manager for a `with` statement. Temporarily change settings
        for the duration of the with.
        """
        return ShowContext(self, kwargs)
    
    def set(self, **kwargs):
        """
        Open a context manager for a `with` statement. Temporarily change settings
        for the duration of the with.
        """
        self.options.set(**kwargs)
        if kwargs:
            self.say.set(**kwargs)
    
    def clone(self, **kwargs):
        """
        Create a new Say instance whose options are chained to this instance's
        options (and thence to Say.options). kwargs become the cloned instance's
        overlay options.
        """
        cloned = Show()
        cloned.options = self.options.push(kwargs)
        return cloned
    
    def _showcore(self, args, kwargs, caller, formatter, opts):
        """
        Do core work of showing the args.
        """
        self.opts = opts
        argtuples = self.get_arg_tuples(caller, args)
        
        # Construct the result string
        valstr = opts.sep.join([ formatter(name, value, caller) for name, value in argtuples ])
        locval = [ self.call_location(caller) + ":  ", valstr ] if opts.where else [ valstr ]

        # Emit the result string, and optionally return it
        retval = self.say(*locval, **kwargs)
        if opts.retvalue:
            return retval
        
    def __call__(self, *args, **kwargs):
        """
        Main entry point for Show objects.
        """
        opts = self.opts = self.options.push(kwargs)
        if not opts.show:
            return
        caller = inspect.currentframe().f_back
        formatter = self.arg_format if not opts.props else self.arg_format_props
        return self._showcore(args, kwargs, caller, formatter, opts)
        
    def items(self, *args, **kwargs):
        """
        Show items of a collection.
        """
        opts = self.options.push(kwargs)
        caller = inspect.currentframe().f_back
        return self._showcore(args, kwargs, caller, self.arg_format_items, opts)
        
    def props(self, *args, **kwargs):
        """
        Show properties of objects.
        """
        opts = self.opts = self.options.push(kwargs)
        if not opts.show:
            return
        if len(args) > 1 and isinstance(args[-1], str):
            used = opts.addflat([ args[-1] ], ['props'])
            args = args[:-1]
        if opts.sep == Show.options.sep:
            opts.sep = '\n\n'
        caller = inspect.currentframe().f_back
        return self._showcore(args, kwargs, caller, self.arg_format_props, opts)
    
        # should this check for and show (perhaps with ^ annotation), properties
        # of object inherited from class?
        
        # if no props, should show normally?
        # Ie less difference between show, show.items, show.props
        # also, maybe more automatic or easy-to-specify truncation of results?
    
    def locals(self, *args, **kwargs):
        """
        Show all local vars, plus any other values mentioned.
        """
        opts = self.opts = self.options.push(kwargs)
        caller = inspect.currentframe().f_back
        assert not args # for now
        locdict = caller.f_locals
        omit = cwsv_or_list(opts.omit)
    
        names = [ n for n in sorted(locdict.keys()) if not n.startswith('@py_assert') and n not in omit ]
    
        # Construct the result string
        valstr = opts.sep.join([ self.arg_format(name, locdict[name], caller) for name in names ])
        locval = [ self.call_location(caller) + ":  ", valstr ] if opts.where else [ valstr ]

        # Emit the result string, and optionally return it
        retval = self.say(*locval, **kwargs)
        if opts.retvalue:
            return retval

    def changed(self, *args, **kwargs):
        """
        Show the local variables, then again only when changed.
        """
        opts = self.opts = self.options.push(kwargs)
        if not opts.show:
            return
        
        caller = inspect.currentframe().f_back
        
        f_locals = caller.f_locals
        _id = id(f_locals)

        valitems  = [ (k, v) for (k, v) in f_locals.items() if \
                                not k.startswith('@py_assert') and \
                                not k.startswith('_') and \
                                not isinstance(v, FUNKY) and \
                                not getattr(v, '__module__', '').startswith( ('IPython', 'site', 'show')) and \
                                not (isInteractive and (k == 'In' or k == 'Out'))
                            ]        
        if args:
            self.say("args = {args!r}")
            argtuples = self.get_arg_tuples(caller, args)
            valitems.extend(argtuples)
        
        valdict = dict(valitems)
        _id = id(f_locals)
        watching = self._watching.get(_id, None)
        if watching is None:
            self._watching[_id] = watching = to_show = valdict
        else:
            to_show = {}
            for k, v in valdict.items():
                if k not in watching or v != watching[k]:
                    to_show[k] = v
                    watching[k] = v
            
                
        omit = cwsv_or_list(opts.omit)
            
        names = [ n for n in sorted(to_show.keys()) if n not in omit ]
        
        # Construct the result string
        if names:
            valstr = opts.sep.join([ self.arg_format(name, to_show[name], caller) for name in names ])
        else:
            valstr = six.u('\u2205')
        locval = [ self.call_location(caller) + ":  ", valstr ] if opts.where else [ valstr ]

        # Emit the result string, and optionally return it
        retval = self.say(*locval, **kwargs)
        if opts.retvalue:
            return retval
            
    watch = changed
    # to be removed soon
        
    def inout(self, func):
        """
        Decorator that shows arguments to a function.
        """
        func_code = func.__code__ if _PY3 else func.func_code
        argnames = func_code.co_varnames[:func_code.co_argcount]
        fname = func.__name__ if _PY3 else func.func_name

        def echo_func(*args, **kwargs):
            argcore = ', '.join('%s=%r' % entry for entry in zip(argnames,args) + kwargs.items())
            callstr = ''.join([fname, '(', argcore, ')'])
            self.say(callstr)
            try:
                retval = func(*args, **kwargs)
                retstr = ''.join([' -> ', repr(retval)])
                self.say(retstr)
                return retval
            except Exception as e:
                raise e

        return echo_func
    
    def retval(self, func):
        """
        Decorator that shows arguments to a function, and return value, once
        the function is complete.
        """ 
        func_code = func.__code__ if _PY3 else func.func_code
        argnames = func_code.co_varnames[:func_code.co_argcount]
        fname = func.__name__ if _PY3 else func.func_name

        def echo_func(*args, **kwargs):
            argcore = ', '.join('%s=%r' % entry for entry in list(zip(argnames,args)) + list(kwargs.items()))
            callstr = ''.join([fname, '(', argcore, ')'])
            try:
                retval = func(*args, **kwargs)
                retstr = ''.join([callstr, ' -> ', repr(retval)])
                self.say(retstr)
                return retval
            except Exception as e:
                retstr = ''.join([callstr, ' -> '])
                self.say(retstr)
                raise e
            
        return echo_func
    
    def prettyprint(self, mode='ansi', sep='\n', indent=2, width=120, depth=5, style='friendly'):
        """
        Convenience method to turn on pretty-printing. Mode can be text or ansi.
        """
        self.set(sep=sep)
        mode = mode.lower()
        from pprint import pformat
        pf = lambda x: pformat(x, indent=indent, width=width, depth=depth)
        if mode == 'text':
            self.set(fmtfunc=pf)
            return
        elif mode == 'ansi':
            if 'Komodo' in os.environ.get('PYDBGP_PATH', ''):
                self.set(fmtfunc=pf)
                return
            try:
                from pygments import highlight
                from pygments.lexers import PythonLexer
                lexer = PythonLexer()
                from pygments.formatters import Terminal256Formatter
                formatter = Terminal256Formatter(style=style)
                self.set(fmtfunc=lambda x: highlight(pf(x), lexer, formatter).strip())
                return
            except ImportError:
                raise ImportWarning('install pygments for ANSI formatting; falling back to plain text')
                self.set(fmtfunc=pf)
                return
            except Exception as e:
                raise e
        else:
            raise ValueError("'{0}' is not a recognized pretty print mode").format(mode)

    # TODO: Give option for showing return value differently
    # TODO: Give this decorator standard show kwargs
    # TODO: Unifiy inout and retval function argument/return value decorators
    # TODO: Figure out why test not working (correct answer, but output caputure fails)
    
class ShowContext(OptionsContext):
    """
    Context helper to support Python's with statement.  Generally called
    from ``with show.settings(...):``
    """
    pass

show = Show()