show / show / core.py

"""Debugging print features. """

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

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'])  # 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 format_escape(s):
    """
    Double { and } characters in a string to 'escape' them so ``str.format``
    doesn't treat them as template characters. NB This is NOT idempotent!
    Escaping more than once (when { or } are present ) = ERROR.
    """
    return s.replace('{', '{{').replace('}', '}}') 
    
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)
    )

    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
    
    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)])
    
    @staticmethod
    def value_repr(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``.
        """
        fvalue = repr(value)
        return format_escape(fvalue)

    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:                
            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'
                fvalue = self.value_repr(value)
                return "{0} ({1} {2}{3}): {4}".format(name, length, itemname, s_or_nothing, fvalue)
            else:
                return "{0}: {1!r}".format(name, value)

    def arg_format_props(self, name, value, caller):
        """
        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
                        propkeys = list(value.__slots__)
                    cdict = value.__class__.__dict__
                    realproperties = [ k for k in cdict.keys() if isinstance(cdict[k], property) ]
                    propkeys.extend(realproperties)
                    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))
            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.options.push(kwargs)
        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.options.push(kwargs)
        if len(args) > 1 and isinstance(args[-1], str):
            used = opts.addflat([ args[-1] ], ['props'])
            args = args[:-1]        
        caller = inspect.currentframe().f_back
        return self._showcore(args, kwargs, caller, self.arg_format_props, opts)
    
class ShowContext(OptionsContext):
    """
    Context helper to support Python's with statement.  Generally called
    from ``with show.settings(...):``
    """
    pass

show = Show()
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.