How to use the birdseye.utils.PY3 function in birdseye

To help you get started, we’ve selected a few birdseye examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github alexmojaki / executing / tests / samples / tracer.py View on Github external
def visit_stmt(self, node):
        # type: (ast.stmt) -> ast.With
        """
        Every statement in the original code becomes:

        with _treetrace_hidden_with_stmt(_tree_index):
            

        where the _treetrace_hidden_with_stmt function is the the corresponding method with the
        TreeTracerBase and traced_file arguments already filled in (see _trace_methods_dict)
        """
        context_expr = self._create_simple_marker_call(
            super(_NodeVisitor, self).generic_visit(node),
            TreeTracerBase._treetrace_hidden_with_stmt)

        if PY3:
            wrapped = ast.With(
                items=[ast.withitem(context_expr=context_expr)],
                body=[node],
            )
        else:
            wrapped = ast.With(
                context_expr=context_expr,
                body=[node],
            )
        ast.copy_location(wrapped, node)
        ast.fix_missing_locations(wrapped)
        return wrapped
github alexmojaki / birdseye / tests / test_utils.py View on Github external
write(u'# coding=utf8\né'.encode('utf8'))
        self.assertEqual(u'é', read())

        write(u'# coding=gbk\né'.encode('gbk'))
        self.assertEqual(u'é', read())

        # Wrong encodings

        write(u'# coding=utf8\né'.encode('gbk'))
        self.assertRaises(UnicodeDecodeError, read)

        write(u'# coding=gbk\né'.encode('utf8'))
        self.assertFalse(u'é' in read())

        # In Python 3 the default encoding is assumed to be UTF8
        if PY3:
            write(u'é'.encode('utf8'))
            self.assertEqual(u'é', read())

            write(u'é'.encode('gbk'))

            # The lack of an encoding when one is needed
            # ultimately raises a SyntaxError
            self.assertRaises(SyntaxError, read)
github alexmojaki / birdseye / tests / test_birdseye.py View on Github external
def byteify(x):
    """
    This converts unicode objects to plain str so that the diffs in test failures
    aren't filled with false differences where there's a u prefix.
    """
    if PY3:
        return x

    if isinstance(x, dict):
        return dict((byteify(key), byteify(value)) for key, value in x.items())
    elif isinstance(x, list):
        return [byteify(element) for element in x]
    elif isinstance(x, unicode):
        return x.encode('utf-8')
    else:
        return x
github alexmojaki / executing / tests / samples / bird.py View on Github external
if isinstance(val, Series):
            for i in _sample_indices(length, samples['pandas_rows']):
                try:
                    k = val.index[i:i + 1].format(sparsify=False)[0]
                    v = val.iloc[i]
                except:
                    pass
                else:
                    add_child(k, v)
            return result

        if (level <= 0 or
                isinstance(val,
                           (str, bytes, range)
                           if PY3 else
                           (str, unicode, xrange))):
            return result

        if isinstance(val, (Sequence, ndarray)) and length is not None:
            for i in _sample_indices(length, samples['list']):
                try:
                    v = val[i]
                except:
                    pass
                else:
                    add_child(str(i), v)

        if isinstance(val, Mapping):
            for k, v in islice(_safe_iter(val, iteritems), samples['dict']):
                add_child(cheap_repr(k), v)
github alexmojaki / birdseye / birdseye / bird.py View on Github external
def trace_this_module(self, context=0, deep=False):
        frame = inspect.currentframe()

        filename = None
        while context >= 0:
            frame = frame.f_back
            filename = inspect.getsourcefile(frame)
            if filename is not None:
                context -= 1
        filename = os.path.abspath(filename)

        if frame.f_globals.get('__name__') != '__main__':
            if PY3 and self._treetrace_hidden_with_stmt.__name__ not in frame.f_globals:
                raise RuntimeError(
                    'To trace an imported module, you must import birdseye before '
                    'importing that module.')
            return

        lines = read_source_file(filename).splitlines()
        lines[:frame.f_lineno] = [''] * frame.f_lineno
        source = '\n'.join(lines)
        self.exec_string(source, filename, frame.f_globals, frame.f_locals, deep)
        sys.exit(0)
github alexmojaki / birdseye / birdseye / tracer.py View on Github external
if len(code_options) > 1:
            # Currently lambdas aren't allowed anyway, but should be in the future
            assert is_lambda(func)
            raise ValueError("Failed to trace lambda. Convert the function to a def.")
        new_func_code = code_options[0]  # type: CodeType

        # Give the new function access to the hooks
        # We have to use the original __globals__ and not a copy
        # because it's the actual module namespace that may get updated by other code
        func.__globals__.update(self._trace_methods_dict(traced_file))

        # http://stackoverflow.com/a/13503277/2482744
        # noinspection PyArgumentList
        new_func = FunctionType(new_func_code, func.__globals__, func.__name__, func.__defaults__, func.__closure__)
        update_wrapper(new_func, func)  # type: FunctionType
        if PY3:
            new_func.__kwdefaults__ = getattr(func, '__kwdefaults__', None)
        new_func.traced_file = traced_file
        return new_func