How to use the bpython._py3compat.py3 function in bpython

To help you get started, we’ve selected a few bpython 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 bpython / bpython / bpython / curtsiesfrontend / replpainter.py View on Github external
s += punctuation_color(', ')
            s += punctuation_color('*')
        marker = object()
        for arg in kwonly:
            s += punctuation_color(', ')
            color = token_color
            if arg_pos:
                color = bolds[color]
            s += color(arg)
            default = kwonly_defaults.get(arg, marker)
            if default is not marker:
                s += punctuation_color('=')
                s += token_color(repr(default))

    if _kwargs:
        if args or _args or (py3 and kwonly):
            s += punctuation_color(', ')
        s += token_color('**%s' % (_kwargs,))
    s += punctuation_color(')')

    return linesplit(s, columns)
github bpython / bpython / bpython / translations / __init__.py View on Github external
# encoding: utf-8

from __future__ import absolute_import

import gettext
import locale
import os.path
import sys

from .. import package_dir
from .._py3compat import py3

translator = None

if py3:

    def _(message):
        return translator.gettext(message)

    def ngettext(singular, plural, n):
        return translator.ngettext(singular, plural, n)


else:

    def _(message):
        return translator.ugettext(message)

    def ngettext(singular, plural, n):
        return translator.ungettext(singular, plural, n)
github bpython / bpython / bpython / importcompletion.py View on Github external
except EnvironmentError:
        filenames = []
    for name in filenames:
        if not any(name.endswith(suffix) for suffix in SUFFIXES):
            # Possibly a package
            if "." in name:
                continue
        elif os.path.isdir(os.path.join(path, name)):
            # Unfortunately, CPython just crashes if there is a directory
            # which ends with a python extension, so work around.
            continue
        for suffix in SUFFIXES:
            if name.endswith(suffix):
                name = name[: -len(suffix)]
                break
        if py3 and name == "badsyntax_pep3120":
            # Workaround for issue #166
            continue
        try:
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", ImportWarning)
                fo, pathname, _ = imp.find_module(name, [path])
        except (ImportError, IOError, SyntaxError):
            continue
        except UnicodeEncodeError:
            # Happens with Python 3 when there is a filename in some
            # invalid encoding
            continue
        else:
            if fo is not None:
                fo.close()
            else:
github bpython / bpython / bpython / curtsiesfrontend / repl.py View on Github external
from bpython.curtsiesfrontend.coderunner import CodeRunner, FakeOutput
from bpython.curtsiesfrontend.filewatch import ModuleChangedEventHandler
from bpython.curtsiesfrontend.interaction import StatusBar
from bpython.curtsiesfrontend.manual_readline import edit_keys
from bpython.curtsiesfrontend import events as bpythonevents
from bpython.curtsiesfrontend.parse import parse as bpythonparse
from bpython.curtsiesfrontend.parse import func_for_letter, color_for_letter
from bpython.curtsiesfrontend.preprocess import preprocess
from bpython.curtsiesfrontend.interpreter import (
    Interp,
    code_finished_will_parse,
)

from curtsies.configfile_keynames import keymap as key_dispatch

if not py3:
    import imp
    import pkgutil


logger = logging.getLogger(__name__)

INCONSISTENT_HISTORY_MSG = "#<---History inconsistent with output shown--->"
CONTIGUITY_BROKEN_MSG = "#<---History contiguity broken by rewind--->"
HELP_MESSAGE = """
Thanks for using bpython!

See http://bpython-interpreter.org/ for more information and
http://docs.bpython-interpreter.org/ for docs.
Please report issues at https://github.com/bpython/bpython/issues

Features:
github ivanov / bipython / bipython / __init__.py View on Github external
# does clever wrapping. I do not (yet).
                for k, i in enumerate(args):
                    if defaults and k + 1 > len(args) - len(defaults):
                        kw = repr(defaults[k - (len(args) - len(defaults))])
                    else:
                        kw = None

                    if not k and str(i) == 'self':
                        color = 'name'
                    else:
                        color = 'token'

                    if k == in_arg or i == in_arg:
                        color = 'bold ' + color

                    if not py3:
                        # See issue #138: We need to format tuple unpacking correctly
                        # We use the undocumented function inspection.strseq() for
                        # that. Fortunately, that madness is gone in Python 3.
                        markup.append((color, inspect.strseq(i, str)))
                    else:
                        markup.append((color, str(i)))
                    if kw is not None:
                        markup.extend([('punctuation', '='),
                                       ('token', kw)])
                    if k != len(args) - 1:
                        markup.append(('punctuation', ', '))

                if varargs:
                    if args:
                        markup.append(('punctuation', ', '))
                    markup.append(('token', '*' + varargs))
github bpython / bpython / bpython / curtsiesfrontend / _internal.py View on Github external
def pager(self, output):
        if not py3 and isinstance(output, str):
            output = output.decode(getpreferredencoding())
        self._repl.pager(output)
github bpython / bpython / bpython / curtsiesfrontend / manual_readline.py View on Github external
"""implementations of simple readline edit operations

just the ones that fit the model of transforming the current line
and the cursor location
based on http://www.bigsmoke.us/readline/shortcuts"""

from bpython.lazyre import LazyReCompile

import inspect
from six import iteritems
from bpython._py3compat import py3

INDENT = 4

# TODO Allow user config of keybindings for these actions
if not py3:
    getargspec = lambda func: inspect.getargspec(func)[0]
else:
    getargspec = lambda func: inspect.signature(func).parameters


class AbstractEdits(object):

    default_kwargs = {
        "line": "hello world",
        "cursor_offset": 5,
        "cut_buffer": "there",
    }

    def __contains__(self, key):
        try:
            self[key]
github bpython / bpython / bpython / repl.py View on Github external
On Python 3.X, encode will be ignored.

        encode should only be used for interactive interpreter input,
        files should always already have an encoding comment or be ASCII.
        By default an encoding line will be added if no filename is given.

        In Python 3, source must be a unicode string
        In Python 2, source may be latin-1 bytestring or unicode string,
        following the interface of code.InteractiveInterpreter.

        Because adding an encoding comment to a unicode string in Python 2
        would cause a syntax error to be thrown which would reference code
        the user did not write, setting encoding to True when source is a
        unicode string in Python 2 will throw a ValueError."""
        # str means bytestring in Py2
        if encode and not py3 and isinstance(source, unicode):
            if encode != "auto":
                raise ValueError("can't add encoding line to unicode input")
            encode = False
        if encode and filename is not None:
            # files have encoding comments or implicit encoding of ASCII
            if encode != "auto":
                raise ValueError("shouldn't add encoding line to file contents")
            encode = False

        if encode and not py3 and isinstance(source, str):
            # encoding makes sense for bytestrings, so long as there
            # isn't already an encoding comment
            comment = inspection.get_encoding_comment(source)
            if comment:
                # keep the existing encoding comment, but add two lines
                # because this interp always adds 2 to stack trace line
github bpython / bpython / bpython / curtsiesfrontend / replpainter.py View on Github external
def formatted_argspec(funcprops, arg_pos, columns, config):
    # Pretty directly taken from bpython.cli
    func = funcprops.func
    args = funcprops.argspec.args
    kwargs = funcprops.argspec.defaults
    _args = funcprops.argspec.varargs
    _kwargs = funcprops.argspec.varkwargs
    is_bound_method = funcprops.is_bound_method
    if py3:
        kwonly = funcprops.argspec.kwonly
        kwonly_defaults = funcprops.argspec.kwonly_defaults or dict()

    arg_color = func_for_letter(config.color_scheme["name"])
    func_color = func_for_letter(config.color_scheme["name"].swapcase())
    punctuation_color = func_for_letter(config.color_scheme["punctuation"])
    token_color = func_for_letter(config.color_scheme["token"])
    bolds = {
        token_color: lambda x: bold(token_color(x)),
        arg_color: lambda x: bold(arg_color(x)),
    }

    s = func_color(func) + arg_color(": (")

    if is_bound_method and isinstance(arg_pos, int):
        # TODO what values could this have?
github bpython / bpython / bpython / urwid.py View on Github external
"""Clear the buffer, redraw the screen and re-evaluate the history"""

        self.evaluating = True
        self.stdout_hist = ""
        self.f_string = ""
        self.buffer = []
        self.scr.erase()
        self.s_hist = []
        # Set cursor position to -1 to prevent paren matching
        self.cpos = -1

        self.prompt(False)

        self.iy, self.ix = self.scr.getyx()
        for line in self.history:
            if py3:
                self.stdout_hist += line + "\n"
            else:
                self.stdout_hist += (
                    line.encode(locale.getpreferredencoding()) + "\n"
                )
            self.print_line(line)
            self.s_hist[-1] += self.f_string
            # I decided it was easier to just do this manually
            # than to make the print_line and history stuff more flexible.
            self.scr.addstr("\n")
            more = self.push(line)
            self.prompt(more)
            self.iy, self.ix = self.scr.getyx()

        self.cpos = 0
        indent = repl.next_indentation(self.s, self.config.tab_length)