Skip to content

MAINT Run pyupgrade following Python2 deprecation #12997

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 8, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions benchmarks/bench_plot_neighbors.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,10 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11),

#------------------------------------------------------------
# varying N
N_results_build = dict([(alg, np.zeros(len(Nrange)))
for alg in algorithms])
N_results_query = dict([(alg, np.zeros(len(Nrange)))
for alg in algorithms])
N_results_build = {alg: np.zeros(len(Nrange))
for alg in algorithms}
N_results_query = {alg: np.zeros(len(Nrange))
for alg in algorithms}

for i, NN in enumerate(Nrange):
print("N = %i (%i out of %i)" % (NN, i + 1, len(Nrange)))
Expand All @@ -61,10 +61,10 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11),

#------------------------------------------------------------
# varying D
D_results_build = dict([(alg, np.zeros(len(Drange)))
for alg in algorithms])
D_results_query = dict([(alg, np.zeros(len(Drange)))
for alg in algorithms])
D_results_build = {alg: np.zeros(len(Drange))
for alg in algorithms}
D_results_query = {alg: np.zeros(len(Drange))
for alg in algorithms}

for i, DD in enumerate(Drange):
print("D = %i (%i out of %i)" % (DD, i + 1, len(Drange)))
Expand All @@ -84,10 +84,10 @@ def barplot_neighbors(Nrange=2 ** np.arange(1, 11),

#------------------------------------------------------------
# varying k
k_results_build = dict([(alg, np.zeros(len(krange)))
for alg in algorithms])
k_results_query = dict([(alg, np.zeros(len(krange)))
for alg in algorithms])
k_results_build = {alg: np.zeros(len(krange))
for alg in algorithms}
k_results_query = {alg: np.zeros(len(krange))
for alg in algorithms}

X = get_data(N, DD, dataset)

Expand Down
2 changes: 1 addition & 1 deletion benchmarks/bench_plot_nmf.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ class _PGNMF(NMF):
def __init__(self, n_components=None, solver='pg', init=None,
tol=1e-4, max_iter=200, random_state=None,
alpha=0., l1_ratio=0., nls_max_iter=10):
super(_PGNMF, self).__init__(
super().__init__(
n_components=n_components, init=init, solver=solver, tol=tol,
max_iter=max_iter, random_state=random_state, alpha=alpha,
l1_ratio=l1_ratio)
Expand Down
6 changes: 3 additions & 3 deletions benchmarks/bench_sample_without_replacement.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,9 +133,9 @@ def bench_sample(sampling, n_population, n_samples):

###########################################################################
# Remove unspecified algorithm
sampling_algorithm = dict((key, value)
for key, value in sampling_algorithm.items()
if key in selected_algorithm)
sampling_algorithm = {key: value
for key, value in sampling_algorithm.items()
if key in selected_algorithm}

###########################################################################
# Perform benchmark
Expand Down
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,6 @@ def setup(app):

# The following is used by sphinx.ext.linkcode to provide links to github
linkcode_resolve = make_linkcode_resolve('sklearn',
u'https://github.com/scikit-learn/'
'https://github.com/scikit-learn/'
'scikit-learn/blob/{revision}/'
'{package}/{path}#L{lineno}')
2 changes: 1 addition & 1 deletion doc/tutorial/machine_learning_map/parse_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class CaselessPreservingLiteral(CaselessLiteral):
instead of as defined.
"""
def __init__( self, matchString ):
super(CaselessPreservingLiteral,self).__init__( matchString.upper() )
super().__init__(matchString.upper())
self.name = "'%s'" % matchString
self.errmsg = "Expected " + self.name
self.myException.msg = self.errmsg
Expand Down
30 changes: 15 additions & 15 deletions doc/tutorial/text_analytics/data/languages/fetch_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@
import codecs

pages = {
u'ar': u'http://ar.wikipedia.org/wiki/%D9%88%D9%8A%D9%83%D9%8A%D8%A8%D9%8A%D8%AF%D9%8A%D8%A7',
u'de': u'http://de.wikipedia.org/wiki/Wikipedia',
u'en': u'https://en.wikipedia.org/wiki/Wikipedia',
u'es': u'http://es.wikipedia.org/wiki/Wikipedia',
u'fr': u'http://fr.wikipedia.org/wiki/Wikip%C3%A9dia',
u'it': u'http://it.wikipedia.org/wiki/Wikipedia',
u'ja': u'http://ja.wikipedia.org/wiki/Wikipedia',
u'nl': u'http://nl.wikipedia.org/wiki/Wikipedia',
u'pl': u'http://pl.wikipedia.org/wiki/Wikipedia',
u'pt': u'http://pt.wikipedia.org/wiki/Wikip%C3%A9dia',
u'ru': u'http://ru.wikipedia.org/wiki/%D0%92%D0%B8%D0%BA%D0%B8%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F',
'ar': 'http://ar.wikipedia.org/wiki/%D9%88%D9%8A%D9%83%D9%8A%D8%A8%D9%8A%D8%AF%D9%8A%D8%A7', # noqa: E501
'de': 'http://de.wikipedia.org/wiki/Wikipedia',
'en': 'https://en.wikipedia.org/wiki/Wikipedia',
'es': 'http://es.wikipedia.org/wiki/Wikipedia',
'fr': 'http://fr.wikipedia.org/wiki/Wikip%C3%A9dia',
'it': 'http://it.wikipedia.org/wiki/Wikipedia',
'ja': 'http://ja.wikipedia.org/wiki/Wikipedia',
'nl': 'http://nl.wikipedia.org/wiki/Wikipedia',
'pl': 'http://pl.wikipedia.org/wiki/Wikipedia',
'pt': 'http://pt.wikipedia.org/wiki/Wikip%C3%A9dia',
'ru': 'http://ru.wikipedia.org/wiki/%D0%92%D0%B8%D0%BA%D0%B8%D0%BF%D0%B5%D0%B4%D0%B8%D1%8F', # noqa: E501
# u'zh': u'http://zh.wikipedia.org/wiki/Wikipedia',
}

html_folder = u'html'
text_folder = u'paragraphs'
short_text_folder = u'short_paragraphs'
html_folder = 'html'
text_folder = 'paragraphs'
short_text_folder = 'short_paragraphs'
n_words_per_short_text = 5


Expand Down Expand Up @@ -93,7 +93,7 @@
groups = np.array_split(words, n_groups)

for group in groups:
small_content = u" ".join(group)
small_content = " ".join(group)

short_text_filename = os.path.join(short_text_lang_folder,
'%s_%04d.txt' % (lang, j))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@

# Predict the result on some short new sentences:
sentences = [
u'This is a language detection test.',
u'Ceci est un test de d\xe9tection de la langue.',
u'Dies ist ein Test, um die Sprache zu erkennen.',
'This is a language detection test.',
'Ceci est un test de d\xe9tection de la langue.',
'Dies ist ein Test, um die Sprache zu erkennen.',
]
predicted = clf.predict(sentences)

for s, p in zip(sentences, predicted):
print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p]))
print('The language of "%s" is "%s"' % (s, dataset.target_names[p]))
Original file line number Diff line number Diff line change
Expand Up @@ -60,11 +60,11 @@

# Predict the result on some short new sentences:
sentences = [
u'This is a language detection test.',
u'Ceci est un test de d\xe9tection de la langue.',
u'Dies ist ein Test, um die Sprache zu erkennen.',
'This is a language detection test.',
'Ceci est un test de d\xe9tection de la langue.',
'Dies ist ein Test, um die Sprache zu erkennen.',
]
predicted = clf.predict(sentences)

for s, p in zip(sentences, predicted):
print(u'The language of "%s" is "%s"' % (s, dataset.target_names[p]))
print('The language of "%s" is "%s"' % (s, dataset.target_names[p]))
2 changes: 1 addition & 1 deletion examples/applications/plot_out_of_core_classification.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def get_minibatch(doc_iter, size, pos_class=positive_class):
Note: size is before excluding invalid docs with no topics assigned.

"""
data = [(u'{title}\n\n{body}'.format(**doc), pos_class in doc['topics'])
data = [('{title}\n\n{body}'.format(**doc), pos_class in doc['topics'])
for doc in itertools.islice(doc_iter, size)
if doc['topics']]
if not len(data):
Expand Down
8 changes: 4 additions & 4 deletions examples/applications/svm_gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
x_min, x_max = -50, 50


class Model(object):
class Model:
"""The Model which hold the data. It implements the
observable in the observer pattern and notifies the
registered observers on change event.
Expand Down Expand Up @@ -76,7 +76,7 @@ def dump_svmlight_file(self, file):
dump_svmlight_file(X, y, file)


class Controller(object):
class Controller:
def __init__(self, model):
self.model = model
self.kernel = Tk.IntVar()
Expand Down Expand Up @@ -139,7 +139,7 @@ def refit(self):
self.fit()


class View(object):
class View:
"""Test docstring. """
def __init__(self, root, controller):
f = Figure()
Expand Down Expand Up @@ -245,7 +245,7 @@ def plot_decision_surface(self, surface, type):
raise ValueError("surface type unknown")


class ControllBar(object):
class ControllBar:
def __init__(self, root, controller):
fm = Tk.Frame(root)
kernel_group = Tk.Frame(fm)
Expand Down
4 changes: 2 additions & 2 deletions examples/applications/wikipedia_principal_eigenvector.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def get_redirects(redirects_filename):
for l, source in enumerate(redirects.keys()):
transitive_target = None
target = redirects[source]
seen = set([source])
seen = {source}
while True:
transitive_target = target
target = redirects.get(target)
Expand Down Expand Up @@ -172,7 +172,7 @@ def get_adjacency_matrix(redirects_filename, page_links_filename, limit=None):
# stop after 5M links to make it possible to work in RAM
X, redirects, index_map = get_adjacency_matrix(
redirects_filename, page_links_filename, limit=5000000)
names = dict((i, name) for name, i in index_map.items())
names = {i: name for name, i in index_map.items()}

print("Computing the principal singular vectors using randomized_svd")
t0 = time()
Expand Down
8 changes: 4 additions & 4 deletions examples/gaussian_process/plot_gpr_noisy_targets.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,8 @@ def f(x):
# the MSE
plt.figure()
plt.plot(x, f(x), 'r:', label=r'$f(x) = x\,\sin(x)$')
plt.plot(X, y, 'r.', markersize=10, label=u'Observations')
plt.plot(x, y_pred, 'b-', label=u'Prediction')
plt.plot(X, y, 'r.', markersize=10, label='Observations')
plt.plot(x, y_pred, 'b-', label='Prediction')
plt.fill(np.concatenate([x, x[::-1]]),
np.concatenate([y_pred - 1.9600 * sigma,
(y_pred + 1.9600 * sigma)[::-1]]),
Expand Down Expand Up @@ -99,8 +99,8 @@ def f(x):
# the MSE
plt.figure()
plt.plot(x, f(x), 'r:', label=r'$f(x) = x\,\sin(x)$')
plt.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label=u'Observations')
plt.plot(x, y_pred, 'b-', label=u'Prediction')
plt.errorbar(X.ravel(), y, dy, fmt='r.', markersize=10, label='Observations')
plt.plot(x, y_pred, 'b-', label='Prediction')
plt.fill(np.concatenate([x, x[::-1]]),
np.concatenate([y_pred - 1.9600 * sigma,
(y_pred + 1.9600 * sigma)[::-1]]),
Expand Down
6 changes: 3 additions & 3 deletions examples/mixture/plot_gmm_covariances.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ def make_ellipses(gmm, ax):
n_classes = len(np.unique(y_train))

# Try GMMs using different types of covariances.
estimators = dict((cov_type, GaussianMixture(n_components=n_classes,
covariance_type=cov_type, max_iter=20, random_state=0))
for cov_type in ['spherical', 'diag', 'tied', 'full'])
estimators = {cov_type: GaussianMixture(n_components=n_classes,
covariance_type=cov_type, max_iter=20, random_state=0)
for cov_type in ['spherical', 'diag', 'tied', 'full']}

n_estimators = len(estimators)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@

score_difference = non_nested_scores - nested_scores

print("Average difference of {0:6f} with std. dev. of {1:6f}."
print("Average difference of {:6f} with std. dev. of {:6f}."
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this intentional? Not that I actually care ;)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have not bothered reverting a few such changes, as long as there are no 500 lines of those, I'm hoping it wouldn't matter much.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fine with me.

.format(score_difference.mean(), score_difference.std()))

# Plot scores on each trial for nested and non-nested CV
Expand Down
20 changes: 10 additions & 10 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@
# We need to import setuptools early, if we want setuptools features,
# as it monkey-patches the 'setup' function
# For some commands, use setuptools
SETUPTOOLS_COMMANDS = set([
SETUPTOOLS_COMMANDS = {
'develop', 'release', 'bdist_egg', 'bdist_rpm',
'bdist_wininst', 'install_egg_info', 'build_sphinx',
'egg_info', 'easy_install', 'upload', 'bdist_wheel',
'--single-version-externally-managed',
])
}
if SETUPTOOLS_COMMANDS.intersection(sys.argv):
import setuptools

Expand All @@ -63,8 +63,8 @@
include_package_data=True,
extras_require={
'alldeps': (
'numpy >= {0}'.format(NUMPY_MIN_VERSION),
'scipy >= {0}'.format(SCIPY_MIN_VERSION),
'numpy >= {}'.format(NUMPY_MIN_VERSION),
'scipy >= {}'.format(SCIPY_MIN_VERSION),
),
},
)
Expand Down Expand Up @@ -111,7 +111,7 @@ def run(self):
# to PyPI at release time.
# The URL of the artifact repositories are configured in the setup.cfg file.

WHEELHOUSE_UPLOADER_COMMANDS = set(['fetch_artifacts', 'upload_all'])
WHEELHOUSE_UPLOADER_COMMANDS = {'fetch_artifacts', 'upload_all'}
if WHEELHOUSE_UPLOADER_COMMANDS.intersection(sys.argv):
import wheelhouse_uploader.cmd

Expand Down Expand Up @@ -190,8 +190,8 @@ def setup_package():
],
cmdclass=cmdclass,
install_requires=[
'numpy>={0}'.format(NUMPY_MIN_VERSION),
'scipy>={0}'.format(SCIPY_MIN_VERSION)
'numpy>={}'.format(NUMPY_MIN_VERSION),
'scipy>={}'.format(SCIPY_MIN_VERSION)
],
**extra_setuptools_args)

Expand All @@ -214,7 +214,7 @@ def setup_package():
metadata['version'] = VERSION
else:
numpy_status = get_numpy_status()
numpy_req_str = "scikit-learn requires NumPy >= {0}.\n".format(
numpy_req_str = "scikit-learn requires NumPy >= {}.\n".format(
NUMPY_MIN_VERSION)

instructions = ("Installation instructions are available on the "
Expand All @@ -224,12 +224,12 @@ def setup_package():
if numpy_status['up_to_date'] is False:
if numpy_status['version']:
raise ImportError("Your installation of Numerical Python "
"(NumPy) {0} is out-of-date.\n{1}{2}"
"(NumPy) {} is out-of-date.\n{}{}"
.format(numpy_status['version'],
numpy_req_str, instructions))
else:
raise ImportError("Numerical Python (NumPy) is not "
"installed.\n{0}{1}"
"installed.\n{}{}"
.format(numpy_req_str, instructions))

from numpy.distutils.core import setup
Expand Down
Loading