summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJustin Mayer <entroP@gmail.com>2020-04-26 09:55:08 +0200
committerJustin Mayer <entroP@gmail.com>2020-04-27 09:45:31 +0200
commitd43b786b300358e8a4cbae4afc4052199a7af762 (patch)
tree8c2231297301b1eb307e3c132ca4710cacd5eef0
parent2cd1d44576ecc4fd0cc532cbb19c2b934ab5c665 (diff)
downloadpelican-d43b786b300358e8a4cbae4afc4052199a7af762.tar.gz
Modernize code base to Python 3+ syntaxremove-legacy
Replaces syntax that was relevant in earlier Python versions but that now has modernized equivalents.
-rw-r--r--docs/conf.py4
-rw-r--r--pelican/__init__.py18
-rw-r--r--pelican/cache.py10
-rw-r--r--pelican/contents.py8
-rw-r--r--pelican/generators.py6
-rw-r--r--pelican/log.py2
-rw-r--r--pelican/paginator.py8
-rw-r--r--pelican/plugins/signals.py3
-rw-r--r--pelican/readers.py4
-rw-r--r--pelican/rstdirectives.py2
-rw-r--r--pelican/server.py2
-rw-r--r--pelican/settings.py2
-rw-r--r--pelican/tests/default_conf.py1
-rw-r--r--pelican/tests/support.py4
-rw-r--r--pelican/tests/test_cache.py2
-rw-r--r--pelican/tests/test_contents.py12
-rw-r--r--pelican/tests/test_generators.py16
-rw-r--r--pelican/tests/test_importer.py12
-rw-r--r--pelican/tests/test_paginator.py4
-rw-r--r--pelican/tests/test_pelican.py10
-rw-r--r--pelican/tests/test_plugins.py7
-rw-r--r--pelican/tests/test_readers.py8
-rw-r--r--pelican/tests/test_rstdirectives.py2
-rw-r--r--pelican/tests/test_server.py4
-rw-r--r--pelican/tests/test_settings.py6
-rw-r--r--pelican/tests/test_testsuite.py2
-rw-r--r--pelican/tests/test_urlwrappers.py6
-rw-r--r--pelican/tests/test_utils.py24
-rwxr-xr-xpelican/tools/pelican_import.py17
-rwxr-xr-xpelican/tools/pelican_quickstart.py33
-rwxr-xr-xpelican/tools/pelican_themes.py11
-rw-r--r--pelican/urlwrappers.py6
-rw-r--r--pelican/utils.py10
-rw-r--r--pelican/writers.py4
-rwxr-xr-xsamples/pelican.conf.py2
-rw-r--r--samples/pelican.conf_FR.py2
-rwxr-xr-xsetup.py1
37 files changed, 104 insertions, 171 deletions
diff --git a/docs/conf.py b/docs/conf.py
index 2be4fbe1..53171646 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
import sys
@@ -23,7 +21,7 @@ release = __version__
version = '.'.join(release.split('.')[:1])
last_stable = __version__
rst_prolog = '''
-.. |last_stable| replace:: :pelican-doc:`{0}`
+.. |last_stable| replace:: :pelican-doc:`{}`
'''.format(last_stable)
# The name of the Pygments (syntax highlighting) style to use.
diff --git a/pelican/__init__.py b/pelican/__init__.py
index e19644e0..40a222ae 100644
--- a/pelican/__init__.py
+++ b/pelican/__init__.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import argparse
import logging
import multiprocessing
@@ -40,7 +38,7 @@ DEFAULT_CONFIG_NAME = 'pelicanconf.py'
logger = logging.getLogger(__name__)
-class Pelican(object):
+class Pelican:
def __init__(self, settings):
"""Pelican initialisation
@@ -255,7 +253,7 @@ def parse_arguments(argv=None):
parser.add_argument('-s', '--settings', dest='settings',
help='The settings of the application, this is '
- 'automatically set to {0} if a file exists with this '
+ 'automatically set to {} if a file exists with this '
'name.'.format(DEFAULT_CONFIG_NAME))
parser.add_argument('-d', '--delete-output-directory',
@@ -494,11 +492,13 @@ def main(argv=None):
pelican, settings = get_instance(args)
readers = Readers(settings)
- reader_descs = sorted(set(['%s (%s)' %
- (type(r).__name__,
- ', '.join(r.file_extensions))
- for r in readers.readers.values()
- if r.enabled]))
+ reader_descs = sorted(
+ {
+ '%s (%s)' % (type(r).__name__, ', '.join(r.file_extensions))
+ for r in readers.readers.values()
+ if r.enabled
+ }
+ )
watchers = {'content': folder_watcher(pelican.path,
readers.extensions,
diff --git a/pelican/cache.py b/pelican/cache.py
index 7d6ee992..646f97bc 100644
--- a/pelican/cache.py
+++ b/pelican/cache.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import hashlib
import logging
import os
@@ -10,7 +8,7 @@ from pelican.utils import mkdir_p
logger = logging.getLogger(__name__)
-class FileDataCacher(object):
+class FileDataCacher:
"""Class that can cache data contained in files"""
def __init__(self, settings, cache_name, caching_policy, load_policy):
@@ -33,7 +31,7 @@ class FileDataCacher(object):
try:
with self._cache_open(self._cache_path, 'rb') as fhandle:
self._cache = pickle.load(fhandle)
- except (IOError, OSError, UnicodeDecodeError) as err:
+ except (OSError, UnicodeDecodeError) as err:
logger.debug('Cannot load cache %s (this is normal on first '
'run). Proceeding with empty cache.\n%s',
self._cache_path, err)
@@ -67,7 +65,7 @@ class FileDataCacher(object):
mkdir_p(self.settings['CACHE_PATH'])
with self._cache_open(self._cache_path, 'wb') as fhandle:
pickle.dump(self._cache, fhandle)
- except (IOError, OSError, pickle.PicklingError) as err:
+ except (OSError, pickle.PicklingError) as err:
logger.warning('Could not save cache %s\n ... %s',
self._cache_path, err)
@@ -116,7 +114,7 @@ class FileStampDataCacher(FileDataCacher):
try:
return self._filestamp_func(filename)
- except (IOError, OSError, TypeError) as err:
+ except (OSError, TypeError) as err:
logger.warning('Cannot get modification stamp for %s\n\t%s',
filename, err)
return ''
diff --git a/pelican/contents.py b/pelican/contents.py
index d01b241f..2bb2e3a0 100644
--- a/pelican/contents.py
+++ b/pelican/contents.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import copy
import datetime
import locale
@@ -22,7 +20,7 @@ from pelican.urlwrappers import (Author, Category, Tag, URLWrapper) # NOQA
logger = logging.getLogger(__name__)
-class Content(object):
+class Content:
"""Represents a content.
:param content: the string to parse, containing the original content.
@@ -216,7 +214,7 @@ class Content(object):
def _expand_settings(self, key, klass=None):
if not klass:
klass = self.__class__.__name__
- fq_key = ('%s_%s' % (klass, key)).upper()
+ fq_key = ('{}_{}'.format(klass, key)).upper()
return self.settings[fq_key].format(**self.url_format)
def get_url_setting(self, key):
@@ -324,7 +322,7 @@ class Content(object):
(?:href|src|poster|data|cite|formaction|action)\s*=\s*)
(?P<quote>["\']) # require value to be quoted
- (?P<path>{0}(?P<value>.*?)) # the url value
+ (?P<path>{}(?P<value>.*?)) # the url value
\2""".format(intrasite_link_regex)
return re.compile(regex, re.X)
diff --git a/pelican/generators.py b/pelican/generators.py
index 232f4759..63e20a0a 100644
--- a/pelican/generators.py
+++ b/pelican/generators.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import calendar
import errno
import fnmatch
@@ -28,7 +26,7 @@ class PelicanTemplateNotFound(Exception):
pass
-class Generator(object):
+class Generator:
"""Baseclass generator"""
def __init__(self, context, settings, path, theme, output_path,
@@ -262,7 +260,7 @@ class _FileLoader(BaseLoader):
if template != self.path or not os.path.exists(self.fullpath):
raise TemplateNotFound(template)
mtime = os.path.getmtime(self.fullpath)
- with open(self.fullpath, 'r', encoding='utf-8') as f:
+ with open(self.fullpath, encoding='utf-8') as f:
source = f.read()
return (source, self.fullpath,
lambda: mtime == os.path.getmtime(self.fullpath))
diff --git a/pelican/log.py b/pelican/log.py
index 0576af2a..ac5034d9 100644
--- a/pelican/log.py
+++ b/pelican/log.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import logging
import os
import sys
diff --git a/pelican/paginator.py b/pelican/paginator.py
index 61899056..9d169045 100644
--- a/pelican/paginator.py
+++ b/pelican/paginator.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import functools
import logging
import os
@@ -13,7 +11,7 @@ PaginationRule = namedtuple(
)
-class Paginator(object):
+class Paginator:
def __init__(self, name, url, object_list, settings, per_page=None):
self.name = name
self.url = url
@@ -61,7 +59,7 @@ class Paginator(object):
page_range = property(_get_page_range)
-class Page(object):
+class Page:
def __init__(self, name, url, object_list, number, paginator, settings):
self.full_name = name
self.name, self.extension = os.path.splitext(name)
@@ -74,7 +72,7 @@ class Page(object):
self.settings = settings
def __repr__(self):
- return '<Page %s of %s>' % (self.number, self.paginator.num_pages)
+ return '<Page {} of {}>'.format(self.number, self.paginator.num_pages)
def has_next(self):
return self.number < self.paginator.num_pages
diff --git a/pelican/plugins/signals.py b/pelican/plugins/signals.py
index 18a745b4..4013360f 100644
--- a/pelican/plugins/signals.py
+++ b/pelican/plugins/signals.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import print_function, unicode_literals
-
from blinker import signal
# Run-level signals:
diff --git a/pelican/readers.py b/pelican/readers.py
index fe53558d..e6d91760 100644
--- a/pelican/readers.py
+++ b/pelican/readers.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import datetime
import logging
import os
@@ -101,7 +99,7 @@ def _filter_discardable_metadata(metadata):
return {name: val for name, val in metadata.items() if val is not _DISCARD}
-class BaseReader(object):
+class BaseReader:
"""Base class to read files.
This class is used to process static files, and it can be inherited for
diff --git a/pelican/rstdirectives.py b/pelican/rstdirectives.py
index dda0e6a7..500c8578 100644
--- a/pelican/rstdirectives.py
+++ b/pelican/rstdirectives.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import re
from docutils import nodes, utils
diff --git a/pelican/server.py b/pelican/server.py
index 8434ded5..6ebce876 100644
--- a/pelican/server.py
+++ b/pelican/server.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import argparse
import logging
import os
diff --git a/pelican/settings.py b/pelican/settings.py
index d508aa36..d219a8f2 100644
--- a/pelican/settings.py
+++ b/pelican/settings.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import copy
import importlib.util
import inspect
diff --git a/pelican/tests/default_conf.py b/pelican/tests/default_conf.py
index 13014572..99f3b6cf 100644
--- a/pelican/tests/default_conf.py
+++ b/pelican/tests/default_conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org'
diff --git a/pelican/tests/support.py b/pelican/tests/support.py
index 327e672d..8a22052e 100644
--- a/pelican/tests/support.py
+++ b/pelican/tests/support.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import locale
import logging
import os
@@ -134,7 +132,7 @@ def skipIfNoExecutable(executable):
res = None
if res is None:
- return unittest.skip('{0} executable not found'.format(executable))
+ return unittest.skip('{} executable not found'.format(executable))
return lambda func: func
diff --git a/pelican/tests/test_cache.py b/pelican/tests/test_cache.py
index 7357cd9f..cc5218b7 100644
--- a/pelican/tests/test_cache.py
+++ b/pelican/tests/test_cache.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
from shutil import rmtree
from tempfile import mkdtemp
diff --git a/pelican/tests/test_contents.py b/pelican/tests/test_contents.py
index 4c23a3da..93f5b212 100644
--- a/pelican/tests/test_contents.py
+++ b/pelican/tests/test_contents.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import datetime
import locale
import logging
@@ -27,7 +25,7 @@ class TestBase(LoggedTestCase):
def setUp(self):
super().setUp()
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.page_kwargs = {
'content': TEST_CONTENT,
'context': {
@@ -56,13 +54,13 @@ class TestBase(LoggedTestCase):
def _copy_page_kwargs(self):
# make a deep copy of page_kwargs
- page_kwargs = dict([(key, self.page_kwargs[key]) for key in
- self.page_kwargs])
+ page_kwargs = {key: self.page_kwargs[key] for key in self.page_kwargs}
for key in page_kwargs:
if not isinstance(page_kwargs[key], dict):
break
- page_kwargs[key] = dict([(subkey, page_kwargs[key][subkey])
- for subkey in page_kwargs[key]])
+ page_kwargs[key] = {
+ subkey: page_kwargs[key][subkey] for subkey in page_kwargs[key]
+ }
return page_kwargs
diff --git a/pelican/tests/test_generators.py b/pelican/tests/test_generators.py
index d559cec9..50e08983 100644
--- a/pelican/tests/test_generators.py
+++ b/pelican/tests/test_generators.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import locale
import os
from shutil import copy, rmtree
@@ -27,7 +25,7 @@ CONTENT_DIR = os.path.join(CUR_DIR, 'content')
class TestGenerator(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.settings = get_settings()
self.settings['READERS'] = {'asc': None}
self.generator = Generator(self.settings.copy(), self.settings,
@@ -403,7 +401,7 @@ class TestArticlesGenerator(unittest.TestCase):
'period' : a tuple of year, month, day according to the time period
"""
old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
settings = get_settings()
settings['YEAR_ARCHIVE_SAVE_AS'] = 'posts/{date:%Y}/index.html'
@@ -788,7 +786,7 @@ class TestTemplatePagesGenerator(unittest.TestCase):
self.temp_content = mkdtemp(prefix='pelicantests.')
self.temp_output = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
rmtree(self.temp_content)
@@ -823,7 +821,7 @@ class TestTemplatePagesGenerator(unittest.TestCase):
self.assertTrue(os.path.exists(output_path))
# output content is correct
- with open(output_path, 'r') as output_file:
+ with open(output_path) as output_file:
self.assertEqual(output_file.read(), 'foo: bar')
@@ -1013,7 +1011,7 @@ class TestStaticGenerator(unittest.TestCase):
f.write("staticcontent")
self.generator.generate_context()
self.generator.generate_output(None)
- with open(self.endfile, "r") as f:
+ with open(self.endfile) as f:
self.assertEqual(f.read(), "staticcontent")
@unittest.skipUnless(MagicMock, 'Needs Mock module')
@@ -1162,7 +1160,7 @@ class TestJinja2Environment(unittest.TestCase):
self.temp_content = mkdtemp(prefix='pelicantests.')
self.temp_output = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
rmtree(self.temp_content)
@@ -1197,7 +1195,7 @@ class TestJinja2Environment(unittest.TestCase):
self.assertTrue(os.path.exists(output_path))
# output content is correct
- with open(output_path, 'r') as output_file:
+ with open(output_path) as output_file:
self.assertEqual(output_file.read(), expected)
def test_jinja2_filter(self):
diff --git a/pelican/tests/test_importer.py b/pelican/tests/test_importer.py
index f7346b9a..709086c0 100644
--- a/pelican/tests/test_importer.py
+++ b/pelican/tests/test_importer.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import locale
import os
import re
@@ -41,7 +39,7 @@ class TestBloggerXmlImporter(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.posts = blogger2fields(BLOGGER_XML_SAMPLE)
def tearDown(self):
@@ -90,7 +88,7 @@ class TestWordpressXmlImporter(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.posts = wp2fields(WORDPRESS_XML_SAMPLE)
self.custposts = wp2fields(WORDPRESS_XML_SAMPLE, True)
@@ -282,9 +280,9 @@ class TestWordpressXmlImporter(unittest.TestCase):
def test_decode_wp_content(self):
""" Check that we can decode a wordpress content string."""
- with open(WORDPRESS_ENCODED_CONTENT_SAMPLE, 'r') as encoded_file:
+ with open(WORDPRESS_ENCODED_CONTENT_SAMPLE) as encoded_file:
encoded_content = encoded_file.read()
- with open(WORDPRESS_DECODED_CONTENT_SAMPLE, 'r') as decoded_file:
+ with open(WORDPRESS_DECODED_CONTENT_SAMPLE) as decoded_file:
decoded_content = decoded_file.read()
self.assertEqual(
decode_wp_content(encoded_content, br=False),
@@ -405,7 +403,7 @@ class TestBuildHeader(unittest.TestCase):
class TestWordpressXMLAttachements(unittest.TestCase):
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.attachments = get_attachments(WORDPRESS_XML_SAMPLE)
def tearDown(self):
diff --git a/pelican/tests/test_paginator.py b/pelican/tests/test_paginator.py
index 9b600a9b..5dc285ae 100644
--- a/pelican/tests/test_paginator.py
+++ b/pelican/tests/test_paginator.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import locale
from jinja2.utils import generate_lorem_ipsum
@@ -19,7 +17,7 @@ class TestPage(unittest.TestCase):
def setUp(self):
super().setUp()
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.page_kwargs = {
'content': TEST_CONTENT,
'context': {
diff --git a/pelican/tests/test_pelican.py b/pelican/tests/test_pelican.py
index 88122846..16131e8a 100644
--- a/pelican/tests/test_pelican.py
+++ b/pelican/tests/test_pelican.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import locale
import logging
import os
@@ -47,7 +45,7 @@ class TestPelican(LoggedTestCase):
self.temp_cache = mkdtemp(prefix='pelican_cache.')
self.maxDiff = None
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
read_settings() # cleanup PYGMENTS_RST_OPTIONS
@@ -60,7 +58,7 @@ class TestPelican(LoggedTestCase):
out, err = subprocess.Popen(
['git', 'diff', '--no-ext-diff', '--exit-code',
'-w', left_path, right_path],
- env={str('PAGER'): str('')},
+ env={'PAGER': ''},
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate()
@@ -131,9 +129,9 @@ class TestPelican(LoggedTestCase):
def test_custom_locale_generation_works(self):
'''Test that generation with fr_FR.UTF-8 locale works'''
if sys.platform == 'win32':
- our_locale = str('French')
+ our_locale = 'French'
else:
- our_locale = str('fr_FR.UTF-8')
+ our_locale = 'fr_FR.UTF-8'
settings = read_settings(path=SAMPLE_FR_CONFIG, override={
'PATH': INPUT_PATH,
diff --git a/pelican/tests/test_plugins.py b/pelican/tests/test_plugins.py
index 4f62c4a5..730aa6d5 100644
--- a/pelican/tests/test_plugins.py
+++ b/pelican/tests/test_plugins.py
@@ -1,6 +1,3 @@
-# -*- coding: utf-8 -*-
-from __future__ import print_function, unicode_literals
-
import os
from contextlib import contextmanager
@@ -84,9 +81,9 @@ class PluginTest(unittest.TestCase):
def test_load_plugins(self):
def get_plugin_names(plugins):
- return set(
+ return {
plugin.NAME if hasattr(plugin, 'NAME') else plugin.__name__
- for plugin in plugins)
+ for plugin in plugins}
# existing namespace plugins
existing_ns_plugins = load_plugins({})
diff --git a/pelican/tests/test_readers.py b/pelican/tests/test_readers.py
index 07590012..3aced39e 100644
--- a/pelican/tests/test_readers.py
+++ b/pelican/tests/test_readers.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import os
from pelican import readers
@@ -92,9 +90,9 @@ class DefaultReaderTest(ReaderTest):
for tag in content:
readers.find_empty_alt(tag, '/test/path')
log_mock.warning.assert_called_with(
- u'Empty alt attribute for image %s in %s',
- u'test-image.png',
- u'/test/path',
+ 'Empty alt attribute for image %s in %s',
+ 'test-image.png',
+ '/test/path',
extra={'limit_msg':
'Other images have empty alt attributes'}
)
diff --git a/pelican/tests/test_rstdirectives.py b/pelican/tests/test_rstdirectives.py
index 0ff28a4a..36623fc4 100644
--- a/pelican/tests/test_rstdirectives.py
+++ b/pelican/tests/test_rstdirectives.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from pelican.tests.support import unittest
try:
diff --git a/pelican/tests/test_server.py b/pelican/tests/test_server.py
index 824e01ef..68747001 100644
--- a/pelican/tests/test_server.py
+++ b/pelican/tests/test_server.py
@@ -7,12 +7,12 @@ from pelican.server import ComplexHTTPRequestHandler
from pelican.tests.support import unittest
-class MockRequest(object):
+class MockRequest:
def makefile(self, *args, **kwargs):
return BytesIO(b"")
-class MockServer(object):
+class MockServer:
pass
diff --git a/pelican/tests/test_settings.py b/pelican/tests/test_settings.py
index d995527c..8f12f3fd 100644
--- a/pelican/tests/test_settings.py
+++ b/pelican/tests/test_settings.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import copy
import locale
import os
@@ -21,7 +19,7 @@ class TestSettingsConfiguration(unittest.TestCase):
"""
def setUp(self):
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.PATH = abspath(dirname(__file__))
default_conf = join(self.PATH, 'default_conf.py')
self.settings = read_settings(default_conf)
@@ -143,7 +141,7 @@ class TestSettingsConfiguration(unittest.TestCase):
# Test that the default locale is set if not specified in settings
# Reset locale to Python's default locale
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
self.assertEqual(self.settings['LOCALE'], DEFAULT_CONFIG['LOCALE'])
configure_settings(self.settings)
diff --git a/pelican/tests/test_testsuite.py b/pelican/tests/test_testsuite.py
index 4f567516..fa930139 100644
--- a/pelican/tests/test_testsuite.py
+++ b/pelican/tests/test_testsuite.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import warnings
from pelican.tests.support import unittest
diff --git a/pelican/tests/test_urlwrappers.py b/pelican/tests/test_urlwrappers.py
index 37af232e..66ae1524 100644
--- a/pelican/tests/test_urlwrappers.py
+++ b/pelican/tests/test_urlwrappers.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
from pelican.tests.support import unittest
from pelican.urlwrappers import Author, Category, Tag, URLWrapper
@@ -40,7 +38,7 @@ class TestURLWrapper(unittest.TestCase):
self.assertNotEqual(tag, author)
# should be equal vs text representing the same name
- self.assertEqual(tag, u'test')
+ self.assertEqual(tag, 'test')
# should not be equal vs binary
self.assertNotEqual(tag, b'test')
@@ -54,7 +52,7 @@ class TestURLWrapper(unittest.TestCase):
self.assertEqual(author, author_equal)
cat_ascii = Category('指導書', settings={})
- self.assertEqual(cat_ascii, u'zhi dao shu')
+ self.assertEqual(cat_ascii, 'zhi dao shu')
def test_slugify_with_substitutions_and_dots(self):
tag = Tag('Tag Dot', settings={'TAG_REGEX_SUBSTITUTIONS': [
diff --git a/pelican/tests/test_utils.py b/pelican/tests/test_utils.py
index 4a03cdc4..f0bc290d 100644
--- a/pelican/tests/test_utils.py
+++ b/pelican/tests/test_utils.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import locale
import logging
import os
@@ -480,9 +478,9 @@ class TestUtils(LoggedTestCase):
old_locale = locale.setlocale(locale.LC_ALL)
if platform == 'win32':
- locale.setlocale(locale.LC_ALL, str('Turkish'))
+ locale.setlocale(locale.LC_ALL, 'Turkish')
else:
- locale.setlocale(locale.LC_ALL, str('tr_TR.UTF-8'))
+ locale.setlocale(locale.LC_ALL, 'tr_TR.UTF-8')
d = utils.SafeDatetime(2012, 8, 29)
@@ -514,9 +512,9 @@ class TestUtils(LoggedTestCase):
old_locale = locale.setlocale(locale.LC_ALL)
if platform == 'win32':
- locale.setlocale(locale.LC_ALL, str('French'))
+ locale.setlocale(locale.LC_ALL, 'French')
else:
- locale.setlocale(locale.LC_ALL, str('fr_FR.UTF-8'))
+ locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
d = utils.SafeDatetime(2012, 8, 29)
@@ -557,7 +555,7 @@ class TestCopy(unittest.TestCase):
def setUp(self):
self.root_dir = mkdtemp(prefix='pelicantests.')
self.old_locale = locale.setlocale(locale.LC_ALL)
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
def tearDown(self):
shutil.rmtree(self.root_dir)
@@ -666,26 +664,26 @@ class TestDateFormatter(unittest.TestCase):
# This test tries to reproduce an issue that
# occurred with python3.3 under macos10 only
if platform == 'win32':
- locale.setlocale(locale.LC_ALL, str('French'))
+ locale.setlocale(locale.LC_ALL, 'French')
else:
- locale.setlocale(locale.LC_ALL, str('fr_FR.UTF-8'))
+ locale.setlocale(locale.LC_ALL, 'fr_FR.UTF-8')
date = utils.SafeDatetime(2014, 8, 14)
# we compare the lower() dates since macos10 returns
# "Jeudi" for %A whereas linux reports "jeudi"
self.assertEqual(
- u'jeudi, 14 août 2014',
+ 'jeudi, 14 août 2014',
utils.strftime(date, date_format="%A, %d %B %Y").lower())
df = utils.DateFormatter()
self.assertEqual(
- u'jeudi, 14 août 2014',
+ 'jeudi, 14 août 2014',
df(date, date_format="%A, %d %B %Y").lower())
# Let us now set the global locale to C:
- locale.setlocale(locale.LC_ALL, str('C'))
+ locale.setlocale(locale.LC_ALL, 'C')
# DateFormatter should still work as expected
# since it is the whole point of DateFormatter
# (This is where pre-2014/4/15 code fails on macos10)
df_date = df(date, date_format="%A, %d %B %Y").lower()
- self.assertEqual(u'jeudi, 14 août 2014', df_date)
+ self.assertEqual('jeudi, 14 août 2014', df_date)
@unittest.skipUnless(locale_available('fr_FR.UTF-8') or
locale_available('French'),
diff --git a/pelican/tools/pelican_import.py b/pelican/tools/pelican_import.py
index b8a8a5c6..917b78c2 100755
--- a/pelican/tools/pelican_import.py
+++ b/pelican/tools/pelican_import.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
import argparse
import logging
@@ -40,7 +39,7 @@ def decode_wp_content(content, br=True):
if start == -1:
content = content + pre_part
continue
- name = "<pre wp-pre-tag-{0}></pre>".format(pre_index)
+ name = "<pre wp-pre-tag-{}></pre>".format(pre_index)
pre_tags[name] = pre_part[start:] + "</pre>"
content = content + pre_part[0:start] + name
pre_index += 1
@@ -154,7 +153,7 @@ def wp2fields(xml, wp_custpost=False):
content = item.find('encoded').string
raw_date = item.find('post_date').string
- if raw_date == u'0000-00-00 00:00:00':
+ if raw_date == '0000-00-00 00:00:00':
date = None
else:
date_object = SafeDatetime.strptime(
@@ -258,7 +257,7 @@ def dc2fields(file):
category_list = {}
posts = []
- with open(file, 'r', encoding='utf-8') as f:
+ with open(file, encoding='utf-8') as f:
for line in f:
# remove final \n
@@ -394,7 +393,7 @@ def posterous2fields(api_token, email, password):
def get_posterous_posts(api_token, email, password, page=1):
base64string = base64.encodestring(
- ("%s:%s" % (email, password)).encode('utf-8')).replace('\n', '')
+ ("{}:{}".format(email, password)).encode('utf-8')).replace('\n', '')
url = ("http://posterous.com/api/v2/users/me/sites/primary/"
"posts?api_token=%s&page=%d") % (api_token, page)
request = urllib_request.Request(url)
@@ -553,7 +552,7 @@ def build_header(title, date, author, categories, tags, slug,
from docutils.utils import column_width
- header = '%s\n%s\n' % (title, '#' * column_width(title))
+ header = '{}\n{}\n'.format(title, '#' * column_width(title))
if date:
header += ':date: %s\n' % date
if author:
@@ -738,7 +737,7 @@ def download_attachments(output_path, urls):
try:
urlretrieve(url, os.path.join(full_path, filename))
locations[url] = os.path.join(localpath, filename)
- except (URLError, IOError) as e:
+ except (URLError, OSError) as e:
# Python 2.7 throws an IOError rather Than URLError
logger.warning("No file could be downloaded from %s\n%s", url, e)
return locations
@@ -828,7 +827,7 @@ def fields2pelican(
new_content = decode_wp_content(content)
else:
paragraphs = content.splitlines()
- paragraphs = ['<p>{0}</p>'.format(p) for p in paragraphs]
+ paragraphs = ['<p>{}</p>'.format(p) for p in paragraphs]
new_content = ''.join(paragraphs)
fp.write(new_content)
@@ -862,7 +861,7 @@ def fields2pelican(
os.remove(html_filename)
- with open(out_filename, 'r', encoding='utf-8') as fs:
+ with open(out_filename, encoding='utf-8') as fs:
content = fs.read()
if out_markup == 'markdown':
# In markdown, to insert a <br />, end a line with two
diff --git a/pelican/tools/pelican_quickstart.py b/pelican/tools/pelican_quickstart.py
index 2e0e2399..50acdcb6 100755
--- a/pelican/tools/pelican_quickstart.py
+++ b/pelican/tools/pelican_quickstart.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
import argparse
import locale
@@ -87,9 +86,9 @@ def ask(question, answer=str, default=None, length=None):
r = ''
while True:
if default:
- r = input('> {0} [{1}] '.format(question, default))
+ r = input('> {} [{}] '.format(question, default))
else:
- r = input('> {0} '.format(question, default))
+ r = input('> {} '.format(question, default))
r = r.strip()
@@ -101,7 +100,7 @@ def ask(question, answer=str, default=None, length=None):
print('You must enter something')
else:
if length and len(r) != length:
- print('Entry must be {0} characters long'.format(length))
+ print('Entry must be {} characters long'.format(length))
else:
break
@@ -111,11 +110,11 @@ def ask(question, answer=str, default=None, length=None):
r = None
while True:
if default is True:
- r = input('> {0} (Y/n) '.format(question))
+ r = input('> {} (Y/n) '.format(question))
elif default is False:
- r = input('> {0} (y/N) '.format(question))
+ r = input('> {} (y/N) '.format(question))
else:
- r = input('> {0} (y/n) '.format(question))
+ r = input('> {} (y/n) '.format(question))
r = r.strip().lower()
@@ -135,9 +134,9 @@ def ask(question, answer=str, default=None, length=None):
r = None
while True:
if default:
- r = input('> {0} [{1}] '.format(question, default))
+ r = input('> {} [{}] '.format(question, default))
else:
- r = input('> {0} '.format(question))
+ r = input('> {} '.format(question))
r = r.strip()
@@ -167,7 +166,7 @@ def ask_timezone(question, default, tzurl):
break
else:
print('Please enter a valid time zone:\n'
- ' (check [{0}])'.format(tzurl))
+ ' (check [{}])'.format(tzurl))
return r
@@ -199,7 +198,7 @@ needed by Pelican.
os.environ.get('VIRTUAL_ENV', os.curdir), '.project')
no_path_was_specified = hasattr(args.path, 'is_default_path')
if os.path.isfile(project) and no_path_was_specified:
- CONF['basedir'] = open(project, 'r').read().rstrip("\n")
+ CONF['basedir'] = open(project).read().rstrip("\n")
print('Using project associated with current virtual environment. '
'Will save to:\n%s\n' % CONF['basedir'])
else:
@@ -300,12 +299,12 @@ needed by Pelican.
try:
os.makedirs(os.path.join(CONF['basedir'], 'content'))
except OSError as e:
- print('Error: {0}'.format(e))
+ print('Error: {}'.format(e))
try:
os.makedirs(os.path.join(CONF['basedir'], 'output'))
except OSError as e:
- print('Error: {0}'.format(e))
+ print('Error: {}'.format(e))
try:
with open(os.path.join(CONF['basedir'], 'pelicanconf.py'),
@@ -318,7 +317,7 @@ needed by Pelican.
fd.write(_template.render(**conf_python))
fd.close()
except OSError as e:
- print('Error: {0}'.format(e))
+ print('Error: {}'.format(e))
try:
with open(os.path.join(CONF['basedir'], 'publishconf.py'),
@@ -327,7 +326,7 @@ needed by Pelican.
fd.write(_template.render(**CONF))
fd.close()
except OSError as e:
- print('Error: {0}'.format(e))
+ print('Error: {}'.format(e))
if automation:
try:
@@ -337,7 +336,7 @@ needed by Pelican.
fd.write(_template.render(**CONF))
fd.close()
except OSError as e:
- print('Error: {0}'.format(e))
+ print('Error: {}'.format(e))
try:
with open(os.path.join(CONF['basedir'], 'Makefile'),
'w', encoding='utf-8') as fd:
@@ -346,7 +345,7 @@ needed by Pelican.
fd.write(_template.render(py_v=py_v, **CONF))
fd.close()
except OSError as e:
- print('Error: {0}'.format(e))
+ print('Error: {}'.format(e))
print('Done. Your new project is available at %s' % CONF['basedir'])
diff --git a/pelican/tools/pelican_themes.py b/pelican/tools/pelican_themes.py
index 03acd9ce..96d07c1f 100755
--- a/pelican/tools/pelican_themes.py
+++ b/pelican/tools/pelican_themes.py
@@ -1,5 +1,4 @@
#!/usr/bin/env python
-# -*- coding: utf-8 -*-
import argparse
import os
@@ -11,7 +10,7 @@ def err(msg, die=None):
"""Print an error message and exits if an exit code is given"""
sys.stderr.write(msg + '\n')
if die:
- sys.exit((die if type(die) is int else 1))
+ sys.exit(die if type(die) is int else 1)
try:
@@ -49,7 +48,7 @@ def main():
help="Show the themes path and exit")
excl.add_argument(
'-V', '--version', action='version',
- version='pelican-themes v{0}'.format(__version__),
+ version='pelican-themes v{}'.format(__version__),
help='Print the version of this script')
parser.add_argument(
@@ -249,12 +248,12 @@ def clean(v=False):
if os.path.islink(path):
if is_broken_link(path):
if v:
- print('Removing {0}'.format(path))
+ print('Removing {}'.format(path))
try:
os.remove(path)
except OSError:
- print('Error: cannot remove {0}'.format(path))
+ print('Error: cannot remove {}'.format(path))
else:
c += 1
- print("\nRemoved {0} broken links".format(c))
+ print("\nRemoved {} broken links".format(c))
diff --git a/pelican/urlwrappers.py b/pelican/urlwrappers.py
index d01611ba..efe09fbc 100644
--- a/pelican/urlwrappers.py
+++ b/pelican/urlwrappers.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import functools
import logging
import os
@@ -10,7 +8,7 @@ logger = logging.getLogger(__name__)
@functools.total_ordering
-class URLWrapper(object):
+class URLWrapper:
def __init__(self, name, settings):
self.settings = settings
self._name = name
@@ -110,7 +108,7 @@ class URLWrapper(object):
"cat/{slug}" Useful for pagination.
"""
- setting = "%s_%s" % (self.__class__.__name__.upper(), key)
+ setting = "{}_{}".format(self.__class__.__name__.upper(), key)
value = self.settings[setting]
if not isinstance(value, str):
logger.warning('%s is set to %s', setting, value)
diff --git a/pelican/utils.py b/pelican/utils.py
index c1b79ed9..d22fb98e 100644
--- a/pelican/utils.py
+++ b/pelican/utils.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import datetime
import fnmatch
import locale
@@ -99,7 +97,7 @@ class SafeDatetime(datetime.datetime):
return super().strftime(fmt)
-class DateFormatter(object):
+class DateFormatter:
'''A date formatter object used as a jinja filter
Uses the `strftime` implementation and makes sure jinja uses the locale
@@ -125,7 +123,7 @@ class DateFormatter(object):
return formatted
-class memoized(object):
+class memoized:
"""Function decorator to cache return values.
If called later with the same arguments, the cached value is returned
@@ -209,7 +207,7 @@ def get_date(string):
try:
return dateutil.parser.parse(string, default=default)
except (TypeError, ValueError):
- raise ValueError('{0!r} is not a valid date'.format(string))
+ raise ValueError('{!r} is not a valid date'.format(string))
@contextmanager
@@ -646,7 +644,7 @@ def get_original_items(items, with_str):
def _warn_source_paths(msg, items, *extra):
args = [len(items)]
args.extend(extra)
- args.extend((x.source_path for x in items))
+ args.extend(x.source_path for x in items)
logger.warning('{}: {}'.format(msg, '\n%s' * len(items)), *args)
# warn if several items have the same lang
diff --git a/pelican/writers.py b/pelican/writers.py
index 7bbd216e..7b14714a 100644
--- a/pelican/writers.py
+++ b/pelican/writers.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
import logging
import os
from urllib.parse import urljoin
@@ -16,7 +14,7 @@ from pelican.utils import (get_relative_path, is_selected_for_writing,
logger = logging.getLogger(__name__)
-class Writer(object):
+class Writer:
def __init__(self, output_path, settings=None):
self.output_path = output_path
diff --git a/samples/pelican.conf.py b/samples/pelican.conf.py
index 2b99ef5b..1fa7c472 100755
--- a/samples/pelican.conf.py
+++ b/samples/pelican.conf.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITESUBTITLE = 'A personal blog.'
diff --git a/samples/pelican.conf_FR.py b/samples/pelican.conf_FR.py
index f87653a4..dc657404 100644
--- a/samples/pelican.conf_FR.py
+++ b/samples/pelican.conf_FR.py
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
AUTHOR = 'Alexis Métaireau'
SITENAME = "Alexis' log"
SITEURL = 'http://blog.notmyidea.org'
diff --git a/setup.py b/setup.py
index 571b1c5e..2d831aa4 100755
--- a/setup.py
+++ b/setup.py
@@ -1,6 +1,5 @@
#!/usr/bin/env python
-from io import open
from os import walk
from os.path import join, relpath