summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Lord <davidism@gmail.com>2020-01-29 20:13:47 -0800
committerDavid Lord <davidism@gmail.com>2020-01-29 22:20:44 -0800
commit337a79f8caeff25422b28771e851c140d5d744ac (patch)
tree42bb52efe6a579da35ef8869dc972d56120e9f5d
parent89b18c5949ecb6b67badda90f5e01895eabc6aa3 (diff)
downloadmarkupsafe-337a79f8caeff25422b28771e851c140d5d744ac.tar.gz
apply pyupgrade
-rw-r--r--.pre-commit-config.yaml5
-rw-r--r--README.rst10
-rw-r--r--bench/runbench.py11
-rw-r--r--docs/conf.py4
-rw-r--r--docs/formatting.rst14
-rw-r--r--docs/html.rst10
-rw-r--r--docs/index.rst4
-rw-r--r--setup.cfg3
-rw-r--r--setup.py11
-rw-r--r--src/markupsafe/__init__.py33
-rw-r--r--src/markupsafe/_constants.py1
-rw-r--r--src/markupsafe/_native.py3
-rw-r--r--tests/test_escape.py23
-rw-r--r--tests/test_exception_custom_html.py3
-rw-r--r--tests/test_leak.py5
-rw-r--r--tests/test_markupsafe.py27
16 files changed, 72 insertions, 95 deletions
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index cdbcfed..7f8d643 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -1,4 +1,9 @@
repos:
+ - repo: https://github.com/asottile/pyupgrade
+ rev: v1.26.2
+ hooks:
+ - id: pyupgrade
+ args: ["--py36-plus"]
- repo: https://github.com/asottile/reorder_python_imports
rev: v1.9.0
hooks:
diff --git a/README.rst b/README.rst
index 1a58058..63ac13c 100644
--- a/README.rst
+++ b/README.rst
@@ -27,17 +27,17 @@ Examples
>>> from markupsafe import Markup, escape
>>> # escape replaces special characters and wraps in Markup
- >>> escape('<script>alert(document.cookie);</script>')
+ >>> escape("<script>alert(document.cookie);</script>")
Markup(u'&lt;script&gt;alert(document.cookie);&lt;/script&gt;')
>>> # wrap in Markup to mark text "safe" and prevent escaping
- >>> Markup('<strong>Hello</strong>')
+ >>> Markup("<strong>Hello</strong>")
Markup('<strong>hello</strong>')
- >>> escape(Markup('<strong>Hello</strong>'))
+ >>> escape(Markup("<strong>Hello</strong>"))
Markup('<strong>hello</strong>')
- >>> # Markup is a text subclass (str on Python 3, unicode on Python 2)
+ >>> # Markup is a str subclass
>>> # methods and operators escape their arguments
>>> template = Markup("Hello <em>%s</em>")
- >>> template % '"World"'
+ >>> template % ('"World"',)
Markup('Hello <em>&#34;World&#34;</em>')
diff --git a/bench/runbench.py b/bench/runbench.py
index 38cf128..f20cd49 100644
--- a/bench/runbench.py
+++ b/bench/runbench.py
@@ -1,9 +1,3 @@
-#!/usr/bin/env python
-"""
- Runs the benchmarks
-"""
-from __future__ import print_function
-
import os
import re
import sys
@@ -24,10 +18,9 @@ def list_benchmarks():
def run_bench(name):
- sys.stdout.write("%-32s" % name)
- sys.stdout.flush()
+ print(name)
Popen(
- [sys.executable, "-mtimeit", "-s", "from bench_%s import run" % name, "run()"]
+ [sys.executable, "-m", "timeit", "-s", f"from bench_{name} import run", "run()"]
).wait()
diff --git a/docs/conf.py b/docs/conf.py
index f349847..46123a3 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -32,11 +32,11 @@ html_sidebars = {
"**": ["localtoc.html", "relations.html", "searchbox.html"],
}
singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}
-html_title = "MarkupSafe Documentation ({})".format(version)
+html_title = f"MarkupSafe Documentation ({version})"
html_show_sourcelink = False
# LaTeX ----------------------------------------------------------------
latex_documents = [
- (master_doc, "MarkupSafe-{}.tex".format(version), html_title, author, "manual")
+ (master_doc, f"MarkupSafe-{version}.tex", html_title, author, "manual")
]
diff --git a/docs/formatting.rst b/docs/formatting.rst
index c425134..c14f917 100644
--- a/docs/formatting.rst
+++ b/docs/formatting.rst
@@ -26,7 +26,7 @@ to use an ``__html_format__`` method.
is escaped.
For example, to implement a ``User`` that wraps its ``name`` in a
-``span`` tag, and adds a link when using the ``'link'`` format
+``span`` tag, and adds a link when using the ``"link"`` format
specifier:
.. code-block:: python
@@ -37,12 +37,12 @@ specifier:
self.name = name
def __html_format__(self, format_spec):
- if format_spec == 'link':
+ if format_spec == "link":
return Markup(
'<a href="/user/{}">{}</a>'
).format(self.id, self.__html__())
elif format_spec:
- raise ValueError('Invalid format spec')
+ raise ValueError("Invalid format spec")
return self.__html__()
def __html__(self):
@@ -53,10 +53,10 @@ specifier:
.. code-block:: pycon
- >>> user = User(3, '<script>')
+ >>> user = User(3, "<script>")
>>> escape(user)
Markup('<span class="user">&lt;script&gt;</span>')
- >>> Markup('<p>User: {user:link}').format(user=user)
+ >>> Markup("<p>User: {user:link}").format(user=user)
Markup('<p>User: <a href="/user/3"><span class="user">&lt;script&gt;</span></a>
See Python's docs on :ref:`format string syntax <python:formatstrings>`.
@@ -70,8 +70,8 @@ formatting.
.. code-block:: pycon
- >>> user = User(3, '<script>')
- >>> Markup('<a href="/user/%d">"%s</a>') % (user.id, user.name)
+ >>> user = User(3, "<script>")
+ >>> Markup('<a href="/user/%d">%s</a>') % (user.id, user.name)
Markup('<a href="/user/3">&lt;script&gt;</a>')
See Python's docs on :ref:`printf-style formatting <python:old-string-formatting>`.
diff --git a/docs/html.rst b/docs/html.rst
index 3a0c11b..dec87af 100644
--- a/docs/html.rst
+++ b/docs/html.rst
@@ -20,11 +20,11 @@ For example, an ``Image`` class might automatically generate an
self.url = url
def __html__(self):
- return '<img src="%s">' % self.url
+ return f'<img src="{self.url}">'
.. code-block:: pycon
- >>> img = Image('/static/logo.png')
+ >>> img = Image("/static/logo.png")
>>> Markup(img)
Markup('<img src="/static/logo.png">')
@@ -40,12 +40,10 @@ should still be escaped:
self.name = name
def __html__(self):
- return '<a href="/user/{}">{}</a>'.format(
- self.id, escape(self.name)
- )
+ return f'<a href="/user/{self.id}">{escape(self.name)}</a>'
.. code-block:: pycon
- >>> user = User(3, '<script>')
+ >>> user = User(3, "<script>")
>>> escape(user)
Markup('<a href="/users/3">&lt;script&gt;</a>')
diff --git a/docs/index.rst b/docs/index.rst
index 71a8f03..5c45e64 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -13,12 +13,12 @@ object. The object won't be escaped anymore, but any text that is used
with it will be, ensuring that the result remains safe to use in HTML.
>>> from markupsafe import escape
->>> hello = escape('<em>Hello</em>')
+>>> hello = escape("<em>Hello</em>")
>>> hello
Markup('&lt;em&gt;Hello&lt;/em&gt;')
>>> escape(hello)
Markup('&lt;em&gt;Hello&lt;/em&gt;')
->>> hello + ' <strong>World</strong>'
+>>> hello + " <strong>World</strong>"
Markup('&lt;em&gt;Hello&lt;/em&gt; &lt;strong&gt;World&lt;/strong&gt;')
diff --git a/setup.cfg b/setup.cfg
index 4b17303..44ee656 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -38,6 +38,3 @@ ignore =
W503
# up to 88 allowed by bugbear B950
max-line-length = 80
-# _compat names and imports will always look bad, ignore warnings
-exclude =
- src/markupsafe/_compat.py
diff --git a/setup.py b/setup.py
index f8eec16..02e0c3f 100644
--- a/setup.py
+++ b/setup.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-
-import io
+import platform
import re
import sys
from distutils.errors import CCompilerError
@@ -12,12 +10,9 @@ from setuptools import find_packages
from setuptools import setup
from setuptools.command.build_ext import build_ext
-with io.open("src/markupsafe/__init__.py", "rt", encoding="utf8") as f:
+with open("src/markupsafe/__init__.py", encoding="utf8") as f:
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
-is_jython = "java" in sys.platform
-is_pypy = hasattr(sys, "pypy_version_info")
-
ext_modules = [Extension("markupsafe._speedups", ["src/markupsafe/_speedups.c"])]
@@ -87,7 +82,7 @@ def show_message(*lines):
print("=" * 74)
-if not (is_pypy or is_jython):
+if platform.python_implementation() not in {"PyPy", "Jython"}:
try:
run_setup(True)
except BuildFailed:
diff --git a/src/markupsafe/__init__.py b/src/markupsafe/__init__.py
index fac362a..71a881e 100644
--- a/src/markupsafe/__init__.py
+++ b/src/markupsafe/__init__.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
Implements an escape function and a Markup string to replace HTML
special characters with safe representations.
@@ -24,11 +23,11 @@ class Markup(str):
it to mark it safe without escaping. To escape the text, use the
:meth:`escape` class method instead.
- >>> Markup('Hello, <em>World</em>!')
+ >>> Markup("Hello, <em>World</em>!")
Markup('Hello, <em>World</em>!')
>>> Markup(42)
Markup('42')
- >>> Markup.escape('Hello, <em>World</em>!')
+ >>> Markup.escape("Hello, <em>World</em>!")
Markup('Hello &lt;em&gt;World&lt;/em&gt;!')
This implements the ``__html__()`` interface that some frameworks
@@ -45,15 +44,15 @@ class Markup(str):
This is a subclass of :class:`str`. It has the same methods, but
escapes their arguments and returns a ``Markup`` instance.
- >>> Markup('<em>%s</em>') % 'foo & bar'
+ >>> Markup("<em>%s</em>") % ("foo & bar",)
Markup('<em>foo &amp; bar</em>')
- >>> Markup('<em>Hello</em> ') + '<foo>'
+ >>> Markup("<em>Hello</em> ") + "<foo>"
Markup('<em>Hello</em> &lt;foo&gt;')
"""
__slots__ = ()
- def __new__(cls, base=u"", encoding=None, errors="strict"):
+ def __new__(cls, base="", encoding=None, errors="strict"):
if hasattr(base, "__html__"):
base = base.__html__()
if encoding is None:
@@ -88,7 +87,7 @@ class Markup(str):
return self.__class__(super().__mod__(arg))
def __repr__(self):
- return "%s(%s)" % (self.__class__.__name__, super().__repr__())
+ return f"{self.__class__.__name__}({super().__repr__()})"
def join(self, seq):
return self.__class__(super().join(map(self.escape, seq)))
@@ -114,7 +113,7 @@ class Markup(str):
"""Convert escaped markup back into a text string. This replaces
HTML entities with the characters they represent.
- >>> Markup('Main &raquo; <em>About</em>').unescape()
+ >>> Markup("Main &raquo; <em>About</em>").unescape()
'Main » <em>About</em>'
"""
from ._constants import HTML_ENTITIES
@@ -139,10 +138,10 @@ class Markup(str):
""":meth:`unescape` the markup, remove tags, and normalize
whitespace to single spaces.
- >>> Markup('Main &raquo;\t<em>About</em>').striptags()
+ >>> Markup("Main &raquo;\t<em>About</em>").striptags()
'Main » About'
"""
- stripped = u" ".join(_striptags_re.sub("", self).split())
+ stripped = " ".join(_striptags_re.sub("", self).split())
return Markup(stripped).unescape()
@classmethod
@@ -247,10 +246,9 @@ class EscapeFormatter(string.Formatter):
elif hasattr(value, "__html__"):
if format_spec:
raise ValueError(
- "Format specifier {0} given, but {1} does not"
- " define __html_format__. A class that defines"
- " __html__ must define __html_format__ to work"
- " with format specifiers.".format(format_spec, type(value))
+ f"Format specifier {format_spec} given, but {type(value)} does not"
+ " define __html_format__. A class that defines __html__ must define"
+ " __html_format__ to work with format specifiers."
)
rv = value.__html__()
else:
@@ -268,8 +266,8 @@ def _escape_argspec(obj, iterable, escape):
return obj
-class _MarkupEscapeHelper(object):
- """Helper for Markup.__mod__"""
+class _MarkupEscapeHelper:
+ """Helper for :meth:`Markup.__mod__`."""
def __init__(self, obj, escape):
self.obj = obj
@@ -291,8 +289,7 @@ class _MarkupEscapeHelper(object):
return float(self.obj)
-# we have to import it down here as the speedups and native
-# modules imports the markup type which is define above.
+# circular import
try:
from ._native import _make_soft_unicode
from ._speedups import escape, escape_silent, soft_unicode as soft_str
diff --git a/src/markupsafe/_constants.py b/src/markupsafe/_constants.py
index a19d214..7638937 100644
--- a/src/markupsafe/_constants.py
+++ b/src/markupsafe/_constants.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
HTML_ENTITIES = {
"AElig": 198,
"Aacute": 193,
diff --git a/src/markupsafe/_native.py b/src/markupsafe/_native.py
index f886a2c..75d9f65 100644
--- a/src/markupsafe/_native.py
+++ b/src/markupsafe/_native.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
"""
Native Python implementation used when the C module is not compiled.
"""
@@ -49,7 +48,7 @@ def soft_str(s):
string, so it will still be marked as safe and won't be escaped
again.
- >>> value = escape('<User 1>')
+ >>> value = escape("<User 1>")
>>> value
Markup('&lt;User 1&gt;')
>>> escape(str(value))
diff --git a/tests/test_escape.py b/tests/test_escape.py
index 788134a..bf53fac 100644
--- a/tests/test_escape.py
+++ b/tests/test_escape.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import pytest
from markupsafe import Markup
@@ -8,22 +7,22 @@ from markupsafe import Markup
("value", "expect"),
(
# empty
- (u"", u""),
+ ("", ""),
# ascii
- (u"abcd&><'\"efgh", u"abcd&amp;&gt;&lt;&#39;&#34;efgh"),
- (u"&><'\"efgh", u"&amp;&gt;&lt;&#39;&#34;efgh"),
- (u"abcd&><'\"", u"abcd&amp;&gt;&lt;&#39;&#34;"),
+ ("abcd&><'\"efgh", "abcd&amp;&gt;&lt;&#39;&#34;efgh"),
+ ("&><'\"efgh", "&amp;&gt;&lt;&#39;&#34;efgh"),
+ ("abcd&><'\"", "abcd&amp;&gt;&lt;&#39;&#34;"),
# 2 byte
- (u"こんにちは&><'\"こんばんは", u"こんにちは&amp;&gt;&lt;&#39;&#34;こんばんは"),
- (u"&><'\"こんばんは", u"&amp;&gt;&lt;&#39;&#34;こんばんは"),
- (u"こんにちは&><'\"", u"こんにちは&amp;&gt;&lt;&#39;&#34;"),
+ ("こんにちは&><'\"こんばんは", "こんにちは&amp;&gt;&lt;&#39;&#34;こんばんは"),
+ ("&><'\"こんばんは", "&amp;&gt;&lt;&#39;&#34;こんばんは"),
+ ("こんにちは&><'\"", "こんにちは&amp;&gt;&lt;&#39;&#34;"),
# 4 byte
(
- u"\U0001F363\U0001F362&><'\"\U0001F37A xyz",
- u"\U0001F363\U0001F362&amp;&gt;&lt;&#39;&#34;\U0001F37A xyz",
+ "\U0001F363\U0001F362&><'\"\U0001F37A xyz",
+ "\U0001F363\U0001F362&amp;&gt;&lt;&#39;&#34;\U0001F37A xyz",
),
- (u"&><'\"\U0001F37A xyz", u"&amp;&gt;&lt;&#39;&#34;\U0001F37A xyz"),
- (u"\U0001F363\U0001F362&><'\"", u"\U0001F363\U0001F362&amp;&gt;&lt;&#39;&#34;"),
+ ("&><'\"\U0001F37A xyz", "&amp;&gt;&lt;&#39;&#34;\U0001F37A xyz"),
+ ("\U0001F363\U0001F362&><'\"", "\U0001F363\U0001F362&amp;&gt;&lt;&#39;&#34;"),
),
)
def test_escape(escape, value, expect):
diff --git a/tests/test_exception_custom_html.py b/tests/test_exception_custom_html.py
index 5f9ffde..5cf1e8e 100644
--- a/tests/test_exception_custom_html.py
+++ b/tests/test_exception_custom_html.py
@@ -1,10 +1,9 @@
-# -*- coding: utf-8 -*-
import pytest
from markupsafe import escape
-class CustomHtmlThatRaises(object):
+class CustomHtmlThatRaises:
def __html__(self):
raise ValueError(123)
diff --git a/tests/test_leak.py b/tests/test_leak.py
index b36a4ce..5ed906a 100644
--- a/tests/test_leak.py
+++ b/tests/test_leak.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import gc
import sys
@@ -18,8 +17,8 @@ def test_markup_leaks():
for _j in range(1000):
escape("foo")
escape("<foo>")
- escape(u"foo")
- escape(u"<foo>")
+ escape("foo")
+ escape("<foo>")
if hasattr(sys, "pypy_version_info"):
gc.collect()
diff --git a/tests/test_markupsafe.py b/tests/test_markupsafe.py
index b489fa3..c17d1a8 100644
--- a/tests/test_markupsafe.py
+++ b/tests/test_markupsafe.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
import pytest
from markupsafe import escape
@@ -36,15 +35,13 @@ def test_type_behavior():
def test_html_interop():
- class Foo(object):
+ class Foo:
def __html__(self):
return "<em>awesome</em>"
- def __unicode__(self):
+ def __str__(self):
return "awesome"
- __str__ = __unicode__
-
assert Markup(Foo()) == "<em>awesome</em>"
result = Markup("<strong>%s</strong>") % Foo()
assert result == "<strong><em>awesome</em></strong>"
@@ -52,17 +49,17 @@ def test_html_interop():
def test_tuple_interpol():
result = Markup("<em>%s:%s</em>") % ("<foo>", "<bar>")
- expect = Markup(u"<em>&lt;foo&gt;:&lt;bar&gt;</em>")
+ expect = Markup("<em>&lt;foo&gt;:&lt;bar&gt;</em>")
assert result == expect
def test_dict_interpol():
result = Markup("<em>%(foo)s</em>") % {"foo": "<foo>"}
- expect = Markup(u"<em>&lt;foo&gt;</em>")
+ expect = Markup("<em>&lt;foo&gt;</em>")
assert result == expect
result = Markup("<em>%(foo)s:%(bar)s</em>") % {"foo": "<foo>", "bar": "<bar>"}
- expect = Markup(u"<em>&lt;foo&gt;:&lt;bar&gt;</em>")
+ expect = Markup("<em>&lt;foo&gt;:&lt;bar&gt;</em>")
assert result == expect
@@ -103,11 +100,11 @@ def test_formatting_empty():
def test_custom_formatting():
- class HasHTMLOnly(object):
+ class HasHTMLOnly:
def __html__(self):
return Markup("<foo>")
- class HasHTMLAndFormat(object):
+ class HasHTMLAndFormat:
def __html__(self):
return Markup("<foo>")
@@ -119,7 +116,7 @@ def test_custom_formatting():
def test_complex_custom_formatting():
- class User(object):
+ class User:
def __init__(self, id, username):
self.id = id
self.username = username
@@ -144,11 +141,11 @@ def test_complex_custom_formatting():
def test_formatting_with_objects():
- class Stringable(object):
+ class Stringable:
def __str__(self):
- return u"строка"
+ return "строка"
- assert Markup("{s}").format(s=Stringable()) == Markup(u"строка")
+ assert Markup("{s}").format(s=Stringable()) == Markup("строка")
def test_all_set():
@@ -161,7 +158,7 @@ def test_all_set():
def test_escape_silent():
assert escape_silent(None) == Markup()
assert escape(None) == Markup(None)
- assert escape_silent("<foo>") == Markup(u"&lt;foo&gt;")
+ assert escape_silent("<foo>") == Markup("&lt;foo&gt;")
def test_splitting():