sys.py3kwarning - python examples

Here are the examples of the python api sys.py3kwarning taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

12 Examples 7

3 View Complete Implementation : pprint.py
Copyright GNU General Public License v3.0
Author : Acmesec
def _sorted(iterable):
    with warnings.catch_warnings():
        if _sys.py3kwarning:
            warnings.filterwarnings("ignore", "comparing unequal types "
                                    "not supported", DeprecationWarning)
        return sorted(iterable)

3 View Complete Implementation : warnings.py
Copyright GNU General Public License v3.0
Author : Acmesec
def warnpy3k(message, category=None, stacklevel=1):
    """Issue a deprecation warning for Python 3.x related changes.

    Warnings are omitted unless Python is started with the -3 option.
    """
    if sys.py3kwarning:
        if category is None:
            category = DeprecationWarning
        warn(message, category, stacklevel+1)

0 View Complete Implementation : case.py
Copyright GNU General Public License v3.0
Author : Acmesec
    def astersatemsEqual(self, expected_seq, actual_seq, msg=None):
        """An unordered sequence specific comparison. It asterts that
        actual_seq and expected_seq have the same element counts.
        Equivalent to::

            self.astertEqual(Counter(iter(actual_seq)),
                             Counter(iter(expected_seq)))

        asterts that each element has the same count in both sequences.
        Example:
            - [0, 1, 1] and [1, 0, 1] compare equal.
            - [0, 0, 1] and [0, 1] compare unequal.
        """
        first_seq, second_seq = list(expected_seq), list(actual_seq)
        with warnings.catch_warnings():
            if sys.py3kwarning:
                # Silence Py3k warning raised during the sorting
                for _msg in ["(code|dict|type) inequality comparisons",
                             "builtin_function_or_method order comparisons",
                             "comparing unequal types"]:
                    warnings.filterwarnings("ignore", _msg, DeprecationWarning)
            try:
                first = collections.Counter(first_seq)
                second = collections.Counter(second_seq)
            except TypeError:
                # Handle case with unhashable elements
                differences = _count_diff_all_purpose(first_seq, second_seq)
            else:
                if first == second:
                    return
                differences = _count_diff_hashable(first_seq, second_seq)

        if differences:
            standardMsg = 'Element counts were not equal:\n'
            lines = ['First has %d, Second has %d:  %r' % diff for diff in differences]
            diffMsg = '\n'.join(lines)
            standardMsg = self._truncateMessage(standardMsg, diffMsg)
            msg = self._formatMessage(msg, standardMsg)
            self.fail(msg)

0 View Complete Implementation : case.py
Copyright GNU General Public License v3.0
Author : bvn-architecture
    def astersatemsEqual(self, expected_seq, actual_seq, msg=None):
        """An unordered sequence specific comparison. It asterts that
        actual_seq and expected_seq have the same element counts.
        Equivalent to::

            self.astertEqual(Counter(iter(actual_seq)),
                             Counter(iter(expected_seq)))

        asterts that each element has the same count in both sequences.
        Example:
            - [0, 1, 1] and [1, 0, 1] compare equal.
            - [0, 0, 1] and [0, 1] compare unequal.
        """
        first_seq, second_seq = list(actual_seq), list(expected_seq)
        with warnings.catch_warnings():
            if sys.py3kwarning:
                # Silence Py3k warning raised during the sorting
                for _msg in ["(code|dict|type) inequality comparisons",
                             "builtin_function_or_method order comparisons",
                             "comparing unequal types"]:
                    warnings.filterwarnings("ignore", _msg, DeprecationWarning)
            try:
                first = collections.Counter(first_seq)
                second = collections.Counter(second_seq)
            except TypeError:
                # Handle case with unhashable elements
                differences = _count_diff_all_purpose(first_seq, second_seq)
            else:
                if first == second:
                    return
                differences = _count_diff_hashable(first_seq, second_seq)

        if differences:
            standardMsg = 'Element counts were not equal:\n'
            lines = ['First has %d, Second has %d:  %r' % diff for diff in differences]
            diffMsg = '\n'.join(lines)
            standardMsg = self._truncateMessage(standardMsg, diffMsg)
            msg = self._formatMessage(msg, standardMsg)
            self.fail(msg)

0 View Complete Implementation : test_support.py
Copyright MIT License
Author : dxwu
@contextlib.contextmanager
def check_py3k_warnings(*filters, **kwargs):
    """Context manager to silence py3k warnings.

    Accept 2-tuples as positional arguments:
        ("message regexp", WarningCategory)

    Optional argument:
     - if 'quiet' is True, it does not fail if a filter catches nothing
        (default False)

    Without argument, it defaults to:
        check_py3k_warnings(("", DeprecationWarning), quiet=False)
    """
    if sys.py3kwarning:
        if not filters:
            filters = (("", DeprecationWarning),)
    else:
        # It should not raise any py3k warning
        filters = ()
    return _filterwarnings(filters, kwargs.get('quiet'))

0 View Complete Implementation : sre_parse.py
Copyright Apache License 2.0
Author : IronLanguages
def _clast_escape(source, escape, nested):
    # handle escape code inside character clast
    code = ESCAPES.get(escape)
    if code:
        return code
    code = CATEGORIES.get(escape)
    if code and code[0] == IN:
        return code
    try:
        c = escape[1:2]
        if c == "x":
            # hexadecimal escape (exactly two digits)
            while source.next in HEXDIGITS and len(escape) < 4:
                escape = escape + source.get()
            escape = escape[2:]
            if len(escape) != 2:
                raise error, "bogus escape: %s" % repr("\\" + escape)
            return LITERAL, int(escape, 16) & 0xff
        elif c in OCTDIGITS:
            # octal escape (up to three digits)
            while source.next in OCTDIGITS and len(escape) < 4:
                escape = escape + source.get()
            escape = escape[1:]
            return LITERAL, int(escape, 8) & 0xff
        elif c in DIGITS:
            raise error, "bogus escape: %s" % repr(escape)
        if len(escape) == 2:
            if sys.py3kwarning and c in ASCIILETTERS:
                import warnings
                if c in 'Uu':
                    warnings.warn('bad escape %s; Unicode escapes are '
                                  'supported only since Python 3.3' % escape,
                                  FutureWarning, stacklevel=nested + 6)
                else:
                    warnings.warnpy3k('bad escape %s' % escape,
                                      DeprecationWarning, stacklevel=nested + 6)
            return LITERAL, ord(escape[1])
    except ValueError:
        past
    raise error, "bogus escape: %s" % repr(escape)

0 View Complete Implementation : sre_parse.py
Copyright Apache License 2.0
Author : IronLanguages
def _escape(source, escape, state, nested):
    # handle escape code in expression
    code = CATEGORIES.get(escape)
    if code:
        return code
    code = ESCAPES.get(escape)
    if code:
        return code
    try:
        c = escape[1:2]
        if c == "x":
            # hexadecimal escape
            while source.next in HEXDIGITS and len(escape) < 4:
                escape = escape + source.get()
            if len(escape) != 4:
                raise ValueError
            return LITERAL, int(escape[2:], 16) & 0xff
        elif c == "0":
            # octal escape
            while source.next in OCTDIGITS and len(escape) < 4:
                escape = escape + source.get()
            return LITERAL, int(escape[1:], 8) & 0xff
        elif c in DIGITS:
            # octal escape *or* decimal group reference (sigh)
            if source.next in DIGITS:
                escape = escape + source.get()
                if (escape[1] in OCTDIGITS and escape[2] in OCTDIGITS and
                    source.next in OCTDIGITS):
                    # got three octal digits; this is an octal escape
                    escape = escape + source.get()
                    return LITERAL, int(escape[1:], 8) & 0xff
            # not an octal escape, so this is a group reference
            group = int(escape[1:])
            if group < state.groups:
                if not state.checkgroup(group):
                    raise error, "cannot refer to open group"
                if state.lookbehind:
                    import warnings
                    warnings.warn('group references in lookbehind '
                                  'astertions are not supported',
                                  RuntimeWarning, stacklevel=nested + 6)
                return GROUPREF, group
            raise ValueError
        if len(escape) == 2:
            if sys.py3kwarning and c in ASCIILETTERS:
                import warnings
                if c in 'Uu':
                    warnings.warn('bad escape %s; Unicode escapes are '
                                  'supported only since Python 3.3' % escape,
                                  FutureWarning, stacklevel=nested + 6)
                else:
                    warnings.warnpy3k('bad escape %s' % escape,
                                      DeprecationWarning, stacklevel=nested + 6)
            return LITERAL, ord(escape[1])
    except ValueError:
        past
    raise error, "bogus escape: %s" % repr(escape)

0 View Complete Implementation : sre_parse.py
Copyright Apache License 2.0
Author : IronLanguages
def parse(str, flags=0, pattern=None):
    # parse 're' pattern into list of (opcode, argument) tuples

    source = Tokenizer(str)

    if pattern is None:
        pattern = Pattern()
    pattern.flags = flags
    pattern.str = str

    p = _parse_sub(source, pattern, 0)
    if (sys.py3kwarning and
        (p.pattern.flags & SRE_FLAG_LOCALE) and
        (p.pattern.flags & SRE_FLAG_UNICODE)):
        import warnings
        warnings.warnpy3k("LOCALE and UNICODE flags are incompatible",
                          DeprecationWarning, stacklevel=5)

    tail = source.get()
    if tail == ")":
        raise error, "unbalanced parenthesis"
    elif tail:
        raise error, "bogus characters at end of regular expression"

    if not (flags & SRE_FLAG_VERBOSE) and p.pattern.flags & SRE_FLAG_VERBOSE:
        # the VERBOSE flag was switched on inside the pattern.  to be
        # on the safe side, we'll parse the whole thing again...
        return parse(str, p.pattern.flags)

    if flags & SRE_FLAG_DEBUG:
        p.dump()

    return p

0 View Complete Implementation : sre_parse.py
Copyright Apache License 2.0
Author : IronLanguages
def parse_template(source, pattern):
    # parse 're' replacement string into list of literals and
    # group references
    s = Tokenizer(source)
    sget = s.get
    p = []
    a = p.append
    def literal(literal, p=p, pappend=a):
        if p and p[-1][0] is LITERAL:
            p[-1] = LITERAL, p[-1][1] + literal
        else:
            pappend((LITERAL, literal))
    sep = source[:0]
    if type(sep) is type(""):
        makechar = chr
    else:
        makechar = unichr
    while 1:
        this = sget()
        if this is None:
            break # end of replacement string
        if this and this[0] == "\\":
            # group
            c = this[1:2]
            if c == "g":
                name = ""
                if s.match("<"):
                    while 1:
                        char = sget()
                        if char is None:
                            raise error, "unterminated group name"
                        if char == ">":
                            break
                        name = name + char
                if not name:
                    raise error, "missing group name"
                try:
                    index = int(name)
                    if index < 0:
                        raise error, "negative group number"
                except ValueError:
                    if not isname(name):
                        raise error, "bad character in group name"
                    try:
                        index = pattern.groupindex[name]
                    except KeyError:
                        msg = "unknown group name: {0!r}".format(name)
                        raise IndexError(msg)
                a((MARK, index))
            elif c == "0":
                if s.next in OCTDIGITS:
                    this = this + sget()
                    if s.next in OCTDIGITS:
                        this = this + sget()
                literal(makechar(int(this[1:], 8) & 0xff))
            elif c in DIGITS:
                isoctal = False
                if s.next in DIGITS:
                    this = this + sget()
                    if (c in OCTDIGITS and this[2] in OCTDIGITS and
                        s.next in OCTDIGITS):
                        this = this + sget()
                        isoctal = True
                        literal(makechar(int(this[1:], 8) & 0xff))
                if not isoctal:
                    a((MARK, int(this[1:])))
            else:
                try:
                    this = makechar(ESCAPES[this][1])
                except KeyError:
                    if sys.py3kwarning and c in ASCIILETTERS:
                        import warnings
                        warnings.warnpy3k('bad escape %s' % this,
                                          DeprecationWarning, stacklevel=4)
                literal(this)
        else:
            literal(this)
    # convert template to groups and literals lists
    i = 0
    groups = []
    groupsappend = groups.append
    literals = [None] * len(p)
    for c, s in p:
        if c is MARK:
            groupsappend((i, s))
            # literal[i] is already None
        else:
            literals[i] = s
        i = i + 1
    return groups, literals

0 View Complete Implementation : test_grammar.py
Copyright Apache License 2.0
Author : IronLanguages
    def test_yield_in_comprehensions(self):
        # Check yield in comprehensions
        def g(): [x for x in [(yield 1)]]

        def check(code, warntext):
            with check_py3k_warnings((warntext, DeprecationWarning)):
                compile(code, '<test string>', 'exec')
            if sys.py3kwarning:
                with warnings.catch_warnings():
                    warnings.filterwarnings('error', category=DeprecationWarning)
                    with self.astertRaises(SyntaxError) as cm:
                        compile(code, '<test string>', 'exec')
                    self.astertIn(warntext, str(cm.exception))

        check("def g(): [(yield x) for x in ()]",
              "'yield' inside list comprehension")
        check("def g(): [x for x in () if not (yield x)]",
              "'yield' inside list comprehension")
        check("def g(): [y for x in () for y in [(yield x)]]",
              "'yield' inside list comprehension")
        check("def g(): {(yield x) for x in ()}",
              "'yield' inside set comprehension")
        check("def g(): {(yield x): x for x in ()}",
              "'yield' inside dict comprehension")
        check("def g(): {x: (yield x) for x in ()}",
              "'yield' inside dict comprehension")
        check("def g(): ((yield x) for x in ())",
              "'yield' inside generator expression")
        with check_py3k_warnings(("'yield' inside list comprehension",
                                  DeprecationWarning)):
            check_syntax_error(self, "clast C: [(yield x) for x in ()]")
        check("clast C: ((yield x) for x in ())",
              "'yield' inside generator expression")
        with check_py3k_warnings(("'yield' inside list comprehension",
                                  DeprecationWarning)):
            check_syntax_error(self, "[(yield x) for x in ()]")
        check("((yield x) for x in ())",
              "'yield' inside generator expression")