diff --git a/src/sage/misc/benchmark.py b/src/sage/misc/benchmark.py index 0309571905d..66b673a6fa0 100644 --- a/src/sage/misc/benchmark.py +++ b/src/sage/misc/benchmark.py @@ -4,6 +4,7 @@ from sage.all import * + def benchmark(n=-1): """ Run a well-chosen range of Sage commands and record the time it @@ -78,6 +79,7 @@ def benchmark(n=-1): break return v, cputime(t) + def bench0(): """ Run a benchmark. @@ -92,12 +94,13 @@ def bench0(): """ desc = """Benchmark 0: Factor the following polynomial over the rational numbers: (x^97+19*x+1)*(x^103-19*x^97+14)*(x^100-1)""" - x = polygen(QQ,"x") + x = polygen(QQ, "x") f = (x**97+19*x+1)*(x**103-19*x**97+14)*(x**100-1) t = cputime() F = f.factor() return (desc, cputime(t)) + def bench1(): """ Run a benchmark. @@ -115,6 +118,7 @@ def bench1(): g = E.gens() return (desc, cputime(t)) + def bench2(): """ Run a benchmark. @@ -131,6 +135,7 @@ def bench2(): a = ZZ(3)**1000001 * ZZ(19)**100001 return (desc, cputime(t)) + def bench3(): """ Run a benchmark. @@ -147,6 +152,7 @@ def bench3(): a = QQ((2, 3))**100001 * QQ((17, 19))**100001 return (desc, cputime(t)) + def bench4(): """ Run a benchmark. @@ -165,6 +171,7 @@ def bench4(): a = f**200 return (desc, cputime(t)) + def bench5(): """ Run a benchmark. @@ -183,6 +190,7 @@ def bench5(): w = [f**50 for _ in range(100)] return (desc, cputime(t)) + def bench6(): """ Run a benchmark. @@ -195,12 +203,13 @@ def bench6(): """ desc = """Compute the p-division polynomials of y^2 = x^3 + 37*x - 997 for primes p < 40.""" - E = EllipticCurve([0,0,0,37,-997]) + E = EllipticCurve([0, 0, 0, 37, -997]) t = cputime() - for p in [2,3,5,7,11,13,17,19,23,29,31,37]: + for p in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]: f = E.division_polynomial(p) return (desc, cputime(t)) + def bench7(): """ Run a benchmark. @@ -213,7 +222,7 @@ def bench7(): """ desc = """Compute the Mordell-Weil group of y^2 = x^3 + 37*x - 997.""" - E = EllipticCurve([0,0,0,37,-997]) + E = EllipticCurve([0, 0, 0, 37, -997]) t = cputime() G = E.gens() return (desc, cputime(t)) diff --git a/src/sage/misc/call.py b/src/sage/misc/call.py index f3a17c09c6e..aa1485975bc 100644 --- a/src/sage/misc/call.py +++ b/src/sage/misc/call.py @@ -17,6 +17,8 @@ ############################################# # Operators ############################################# + + class AttrCallObject: def __init__(self, name, args, kwds): """ diff --git a/src/sage/misc/compat.py b/src/sage/misc/compat.py index e374cf97aac..32a4f240a41 100644 --- a/src/sage/misc/compat.py +++ b/src/sage/misc/compat.py @@ -1,6 +1,6 @@ """Cross-platform compatibility routines and wrappers.""" -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2017 William Stein # # This program is free software: you can redistribute it and/or modify @@ -8,7 +8,7 @@ # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** import os import subprocess diff --git a/src/sage/misc/copying.py b/src/sage/misc/copying.py index cec1a5189cd..e5e24562c20 100644 --- a/src/sage/misc/copying.py +++ b/src/sage/misc/copying.py @@ -14,7 +14,7 @@ def __repr__(self): return "Type license() to see the full license text." def __str__(self): - with open(os.path.join(SAGE_ROOT,'COPYING.txt')) as f: + with open(os.path.join(SAGE_ROOT, 'COPYING.txt')) as f: return f.read() diff --git a/src/sage/misc/decorators.py b/src/sage/misc/decorators.py index f0b34b8843d..029687cb0b1 100644 --- a/src/sage/misc/decorators.py +++ b/src/sage/misc/decorators.py @@ -13,7 +13,7 @@ - Julian Rueth (2014-03-19): added ``decorator_keywords`` decorator """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2009 Tim Dumol # 2010,2011 Johan S. R. Nielsen # 2011 Simon King @@ -24,7 +24,7 @@ # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** from functools import (partial, update_wrapper, WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES) @@ -155,10 +155,10 @@ def sage_wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES): 81 """ - #TRAC 9919: Workaround for bug in @update_wrapper when used with - #non-function callables. + # TRAC 9919: Workaround for bug in @update_wrapper when used with + # non-function callables. assigned = set(assigned).intersection(set(dir(wrapped))) - #end workaround + # end workaround def f(wrapper, assigned=assigned, updated=updated): update_wrapper(wrapper, wrapped, assigned=assigned, updated=updated) @@ -168,9 +168,9 @@ def f(wrapper, assigned=assigned, updated=updated): wrapper.__wrapped__ = wrapped wrapper._sage_src_ = lambda: sage_getsource(wrapped) wrapper._sage_src_lines_ = lambda: sage_getsourcelines(wrapped) - #Getting the signature right in documentation by Sphinx (Issue 9976) - #The attribute _sage_argspec_() is read by Sphinx if present and used - #as the argspec of the function instead of using reflection. + # Getting the signature right in documentation by Sphinx (Issue 9976) + # The attribute _sage_argspec_() is read by Sphinx if present and used + # as the argspec of the function instead of using reflection. wrapper._sage_argspec_ = lambda: sage_getargspec(wrapped) return wrapper return f @@ -424,7 +424,7 @@ def listForNone(l): newArgs = [self.name + opt for opt in self.options.keys()] args = (argspec.args if argspec.args is not None else []) + newArgs defaults = (argspec.defaults if argspec.defaults is not None else ()) \ - + tuple(self.options.values()) + + tuple(self.options.values()) # Note: argspec.defaults is not always a tuple for some reason return FullArgSpec(args, argspec.varargs, argspec.varkw, defaults, kwonlyargs=[], kwonlydefaults=None, annotations={}) @@ -496,9 +496,9 @@ def wrapper(*args, **kwds): options.update(kwds) return func(*args, **options) - #Add the options specified by @options to the signature of the wrapped - #function in the Sphinx-generated documentation (Issue 9976), using the - #special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) + # Add the options specified by @options to the signature of the wrapped + # function in the Sphinx-generated documentation (Issue 9976), using the + # special attribute _sage_argspec_ (see e.g. sage.misc.sageinspect) def argspec(): argspec = sage_getargspec(func) args = ((argspec.args if argspec.args is not None else []) + @@ -659,6 +659,7 @@ def wrapper(*args, **kwds): return wrapper + class specialize: r""" A decorator generator that returns a decorator that in turn @@ -697,6 +698,7 @@ def __init__(self, *args, **kwargs): def __call__(self, f): return sage_wraps(f)(partial(f, *self.args, **self.kwargs)) + def decorator_keywords(func): r""" A decorator for decorators with optional keyword arguments. @@ -731,7 +733,7 @@ def decorator_keywords(func): @sage_wraps(func) def wrapped(f=None, **kwargs): if f is None: - return sage_wraps(func)(lambda f:func(f, **kwargs)) + return sage_wraps(func)(lambda f: func(f, **kwargs)) else: return func(f, **kwargs) return wrapped diff --git a/src/sage/misc/edit_module.py b/src/sage/misc/edit_module.py index 63232e89a81..cf39a6d2675 100644 --- a/src/sage/misc/edit_module.py +++ b/src/sage/misc/edit_module.py @@ -46,14 +46,14 @@ # we can set some defaults, however. Add your own if you like. template_defaults = { - 'vi' : Template('vi -c ${line} ${file}'), - 'vim' : Template('vim -c ${line} ${file}'), - 'emacs' : Template('emacs ${opts} +${line} ${file}'), - 'nedit-nc' : Template('nedit-nc -line ${line} ${file}'), - 'nedit-client' : Template('nedit-client -line ${line} ${file}'), - 'ncl' : Template('ncl -line ${line} ${file}'), - 'gedit' : Template('gedit +${line} ${file} &'), - 'kate' : Template('kate -u --line +${line} ${file} &') } + 'vi': Template('vi -c ${line} ${file}'), + 'vim': Template('vim -c ${line} ${file}'), + 'emacs': Template('emacs ${opts} +${line} ${file}'), + 'nedit-nc': Template('nedit-nc -line ${line} ${file}'), + 'nedit-client': Template('nedit-client -line ${line} ${file}'), + 'ncl': Template('ncl -line ${line} ${file}'), + 'gedit': Template('gedit +${line} ${file} &'), + 'kate': Template('kate -u --line +${line} ${file} &')} def file_and_line(obj): diff --git a/src/sage/misc/explain_pickle.py b/src/sage/misc/explain_pickle.py index fe62f5ea841..602572212eb 100644 --- a/src/sage/misc/explain_pickle.py +++ b/src/sage/misc/explain_pickle.py @@ -144,7 +144,7 @@ """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2009 Carl Witty # # This program is free software: you can redistribute it and/or modify @@ -152,7 +152,7 @@ # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** import pickletools @@ -258,6 +258,7 @@ def explain_pickle(pickle=None, file=None, compress=True, **kwargs): return explain_pickle_string(p, **kwargs) + def explain_pickle_string(pickle, in_current_sage=False, default_assumptions=False, eval=False, preparse=True, pedantic=False): @@ -295,6 +296,8 @@ def explain_pickle_string(pickle, in_current_sage=False, valid_name_re = re.compile('^[a-zA-Z_][a-zA-Z0-9_]*$') + + def name_is_valid(name): r""" Test whether a string is a valid Python identifier. (We use a @@ -318,6 +321,7 @@ def name_is_valid(name): # This string is used as the representation of a mark. the_mark = 'mark' + class PickleObject: r""" Pickles have a stack-based virtual machine. The :func:`explain_pickle` @@ -374,6 +378,7 @@ def _sage_input_(self, sib, coerced): self.immutable = True return self.expression + class PickleDict: r""" An object which can be used as the value of a :class:`PickleObject`. The items @@ -394,6 +399,7 @@ def __init__(self, items): """ self.items = items + class PickleInstance: r""" An object which can be used as the value of a :class:`PickleObject`. Unlike @@ -412,6 +418,7 @@ def __init__(self, klass): """ self.klass = klass + class PickleExplainer: r""" An interpreter for the pickle virtual machine, that executes @@ -831,9 +838,9 @@ def _APPENDS_helper(self, lst, slice): lst.expression = self.sib(lst.value) elif isinstance(lst, PickleObject) or self.default_assumptions: if isinstance(lst.value, list) or \ - (isinstance(lst.value, PickleInstance) and - issubclass(lst.value.klass, list)) or \ - self.default_assumptions: + (isinstance(lst.value, PickleInstance) and + issubclass(lst.value.klass, list)) or \ + self.default_assumptions: if len(slice) > 1: self.sib.command(lst, self.sib.name('list').extend(lst, slice)) else: @@ -1105,10 +1112,10 @@ def BUILD(self): slots = state[1].value state = state[0].value d = self.sib.getattr(obj, '__dict__') - for k,v in state.items: + for k, v in state.items: self.sib.command(obj, self.sib.assign(d[k], v)) if slots is not None: - for k,v in slots.items: + for k, v in slots.items: if isinstance(k, PickleObject) and isinstance(k.value, str): self.sib.command(obj, self.sib.assign(self.sib.getattr(obj, k.value), v)) else: @@ -2473,6 +2480,7 @@ def unpickle_instantiate(fn, args): unpickle_persistent_loader = None + def unpickle_persistent(s): r""" Takes an integer index and returns the persistent object with that @@ -2985,6 +2993,7 @@ def __setstate__(self, state): self.x = state[1]['y'] self.y = state[0]['x'] + class TestGlobalOldName: r""" A featureless new-style class. When you try to unpickle an instance @@ -3032,6 +3041,7 @@ def __repr__(self): register_unpickle_override('sage.misc.explain_pickle', 'TestGlobalOldName', TestGlobalNewName, call_name=('sage.misc.explain_pickle', 'TestGlobalNewName')) + class TestGlobalFunnyName: r""" A featureless new-style class which has a name that's not a legal @@ -3065,5 +3075,5 @@ def __repr__(self): TestGlobalFunnyName.__name__ = "funny$name" -#This crashed Sphinx. Instead, we manually execute this just before the test. -#globals()['funny$name'] = TestGlobalFunnyName +# This crashed Sphinx. Instead, we manually execute this just before the test. +# globals()['funny$name'] = TestGlobalFunnyName diff --git a/src/sage/misc/flatten.py b/src/sage/misc/flatten.py index 889cf2e9d1d..98ba3b7e577 100644 --- a/src/sage/misc/flatten.py +++ b/src/sage/misc/flatten.py @@ -72,9 +72,9 @@ def flatten(in_list, ltypes=(list, tuple), max_level=sys.maxsize): while isinstance(new_list[index], ltypes) and current_level < max_level: v = list(new_list[index]) len_v = len(v) - new_list[index : index + 1] = v + new_list[index: index + 1] = v old_level = level_list[index] - level_list[index : index + 1] = [0] * len_v + level_list[index: index + 1] = [0] * len_v if len_v: current_level += 1 level_list[index + len_v - 1] = old_level + 1 diff --git a/src/sage/misc/func_persist.py b/src/sage/misc/func_persist.py index 65b6d536d79..0b7f200ad58 100644 --- a/src/sage/misc/func_persist.py +++ b/src/sage/misc/func_persist.py @@ -45,6 +45,7 @@ def bern(n): from sage.misc import persist + class func_persist: r""" Put ``@func_persist`` right before your function diff --git a/src/sage/misc/html.py b/src/sage/misc/html.py index 057698469ac..1fe74334d53 100644 --- a/src/sage/misc/html.py +++ b/src/sage/misc/html.py @@ -10,14 +10,14 @@ renderable in a browser-based notebook with the help of MathJax. """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2008 William Stein # # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** import re diff --git a/src/sage/misc/latex.py b/src/sage/misc/latex.py index ec3ee067075..faa83396d57 100644 --- a/src/sage/misc/latex.py +++ b/src/sage/misc/latex.py @@ -687,7 +687,7 @@ def _run_latex_(filename, debug=False, density=150, engine=None, png=False, do_i from sage.features.dvipng import dvipng if png: if ((not engine or engine == "latex") - and not (dvipng().is_present() or ImageMagick().is_present())): + and not (dvipng().is_present() or ImageMagick().is_present())): print() print("Error: neither dvipng nor convert (from the ImageMagick suite)") print("appear to be installed. Displaying LaTeX, PDFLaTeX output") diff --git a/src/sage/misc/latex_macros.py b/src/sage/misc/latex_macros.py index 93fb11fbf48..3ac23ff9c6e 100644 --- a/src/sage/misc/latex_macros.py +++ b/src/sage/misc/latex_macros.py @@ -128,15 +128,15 @@ def convert_latex_macro_to_mathjax(macro): right_bracket = macro.find('[') if left_bracket >= 0: right_bracket = macro.find(']') - num_args = int(macro[left_bracket + 1 : right_bracket]) + num_args = int(macro[left_bracket + 1: right_bracket]) else: num_args = 0 start_name = macro.find('{') + 1 # add one to go past the backslash end_name = macro.find('}') - name = macro[start_name + 1 : end_name] + name = macro[start_name + 1: end_name] start_defn = macro.find('{', end_name) end_defn = macro.rfind('}') - defn = macro[start_defn + 1 : end_defn] + defn = macro[start_defn + 1: end_defn] if num_args == 0: return name, defn else: @@ -197,6 +197,7 @@ def sage_latex_macros(): """ return [produce_latex_macro(*x) for x in macros] + latex_macros + sage_configurable_latex_macros + def sage_mathjax_macros(): r""" Return Sage's macro definitions for usage with MathJax. diff --git a/src/sage/misc/lazy_format.py b/src/sage/misc/lazy_format.py index b58ea155862..372f5a8dd0a 100644 --- a/src/sage/misc/lazy_format.py +++ b/src/sage/misc/lazy_format.py @@ -94,7 +94,7 @@ def __mod__(self, args): sage: form%"params" """ - if hasattr(self, "_args"): # self is already bound... + if hasattr(self, "_args"): # self is already bound... self = LazyFormat(""+self) self._args = args return self diff --git a/src/sage/misc/mathml.py b/src/sage/misc/mathml.py index bdb0e6fffe0..7d38ad19128 100644 --- a/src/sage/misc/mathml.py +++ b/src/sage/misc/mathml.py @@ -5,7 +5,7 @@ method _mathml_(self) that returns its MathML representation. """ -#***************************************************************************** +# ***************************************************************************** # # Sage: Open Source Mathematical Software # @@ -21,7 +21,7 @@ # The full text of the GPL is available at: # # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** def list_function(x): diff --git a/src/sage/misc/mrange.py b/src/sage/misc/mrange.py index 679ed3fd460..e0c2951329d 100644 --- a/src/sage/misc/mrange.py +++ b/src/sage/misc/mrange.py @@ -10,7 +10,7 @@ - Jon Hanke """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2006 William Stein # # This program is free software: you can redistribute it and/or modify @@ -18,7 +18,7 @@ # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** from sage.misc.misc_c import prod diff --git a/src/sage/misc/namespace_package.py b/src/sage/misc/namespace_package.py index eaa05bdfd71..e2de10b5bfb 100644 --- a/src/sage/misc/namespace_package.py +++ b/src/sage/misc/namespace_package.py @@ -3,6 +3,7 @@ """ from importlib import import_module + def install_doc(package, doc): """ Install the docstring ``doc`` to the package. @@ -19,6 +20,7 @@ def install_doc(package, doc): pkg.__doc__ = doc # enable sage.package? pkg.getdoc = lambda: doc # enable help(sage.package) + def install_dict(package, dic): """ Install ``dic`` to the ``__dict__`` of the package. diff --git a/src/sage/misc/package.py b/src/sage/misc/package.py index b63351a6d4f..0eabcfdb20f 100644 --- a/src/sage/misc/package.py +++ b/src/sage/misc/package.py @@ -66,7 +66,7 @@ def pkgname_split(name): sage: pkgname_split('hello_world-1.2') ['hello_world', '1.2'] """ - return (name.split('-',1) + [''])[:2] + return (name.split('-', 1) + [''])[:2] def pip_remote_version(pkg, pypi_url=DEFAULT_PYPI, ignore_URLError=False): @@ -356,6 +356,7 @@ def list_packages(*pkg_types: str, pkg_sources: List[str] = ['normal', 'pip', 's return pkgs + def _spkg_inst_dirs(): """ Generator for the installation manifest directories as resolved paths. @@ -379,6 +380,7 @@ def _spkg_inst_dirs(): yield inst_dir last_inst_dir = inst_dir + def installed_packages(exclude_pip=True): """ Return a dictionary of all installed packages, with version numbers. diff --git a/src/sage/misc/prandom.py b/src/sage/misc/prandom.py index 800ed60aedd..307385d9a99 100644 --- a/src/sage/misc/prandom.py +++ b/src/sage/misc/prandom.py @@ -57,6 +57,7 @@ from sage.misc.randstate import current_randstate + def _pyrand(): r""" A tiny private helper function to return an instance of @@ -75,6 +76,7 @@ def _pyrand(): """ return current_randstate().python_random() + def getrandbits(k): r""" getrandbits(k) -> x. Generates a long int with k random bits. @@ -90,6 +92,7 @@ def getrandbits(k): """ return _pyrand().getrandbits(k) + def randrange(start, stop=None, step=1): r""" Choose a random item from range(start, stop[, step]). @@ -121,6 +124,7 @@ def randrange(start, stop=None, step=1): """ return _pyrand().randrange(start, stop, step) + def randint(a, b): r""" Return random integer in range [a, b], including both end points. @@ -136,6 +140,7 @@ def randint(a, b): """ return _pyrand().randint(a, b) + def choice(seq): r""" Choose a random element from a non-empty sequence. @@ -149,6 +154,7 @@ def choice(seq): """ return _pyrand().choice(seq) + def shuffle(x): r""" x, random=random.random -> shuffle list x in place; return None. @@ -162,6 +168,7 @@ def shuffle(x): """ return _pyrand().shuffle(x) + def sample(population, k): r""" Choose k unique random elements from a population sequence. @@ -201,6 +208,7 @@ def sample(population, k): """ return _pyrand().sample(population, k) + def random(): r""" Get the next random number in the range [0.0, 1.0). @@ -214,6 +222,7 @@ def random(): """ return _pyrand().random() + def uniform(a, b): r""" Get a random number in the range [a, b). @@ -234,6 +243,7 @@ def uniform(a, b): """ return _pyrand().uniform(a, b) + def betavariate(alpha, beta): r""" Beta distribution. @@ -255,6 +265,7 @@ def betavariate(alpha, beta): """ return _pyrand().betavariate(alpha, beta) + def expovariate(lambd): r""" Exponential distribution. @@ -282,6 +293,7 @@ def expovariate(lambd): """ return _pyrand().expovariate(lambd) + def gammavariate(alpha, beta): r""" Gamma distribution. Not the gamma function! @@ -301,6 +313,7 @@ def gammavariate(alpha, beta): """ return _pyrand().gammavariate(alpha, beta) + def gauss(mu, sigma): r""" Gaussian distribution. @@ -320,6 +333,7 @@ def gauss(mu, sigma): """ return _pyrand().gauss(mu, sigma) + def lognormvariate(mu, sigma): r""" Log normal distribution. @@ -335,6 +349,7 @@ def lognormvariate(mu, sigma): """ return _pyrand().lognormvariate(mu, sigma) + def normalvariate(mu, sigma): r""" Normal distribution. @@ -352,6 +367,7 @@ def normalvariate(mu, sigma): """ return _pyrand().normalvariate(mu, sigma) + def vonmisesvariate(mu, kappa): r""" Circular data distribution. @@ -370,6 +386,7 @@ def vonmisesvariate(mu, kappa): """ return _pyrand().vonmisesvariate(mu, kappa) + def paretovariate(alpha): r""" Pareto distribution. alpha is the shape parameter. @@ -383,6 +400,7 @@ def paretovariate(alpha): """ return _pyrand().paretovariate(alpha) + def weibullvariate(alpha, beta): r""" Weibull distribution. diff --git a/src/sage/misc/profiler.py b/src/sage/misc/profiler.py index a8e3592d935..82746c8f023 100644 --- a/src/sage/misc/profiler.py +++ b/src/sage/misc/profiler.py @@ -7,13 +7,13 @@ - Martin Albrecht """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2006 William Stein # 2006 David Harvey # # Distributed under the terms of the GNU General Public License (GPL) # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** from sage.misc.timing import cputime import inspect @@ -100,7 +100,7 @@ def clear(self): def __call__(self, message=None): """ Adds a checkpoint. """ - entry_times = [fn() for fn in self._cputime_functions ] + entry_times = [fn() for fn in self._cputime_functions] frame = inspect.currentframe().f_back try: @@ -120,7 +120,7 @@ def __call__(self, message=None): self._active_details = (line_number, context, message) - self._last_cputime = [fn() for fn in self._cputime_functions ] + self._last_cputime = [fn() for fn in self._cputime_functions] if self._verbose: print(self.print_last()) sys.stdout.flush() @@ -174,4 +174,4 @@ def print_last(self): return "%9.3fs -- %s" % (time_used, message) -## end of file +# end of file diff --git a/src/sage/misc/proof.py b/src/sage/misc/proof.py index 12a14869fd5..b5085111514 100644 --- a/src/sage/misc/proof.py +++ b/src/sage/misc/proof.py @@ -2,5 +2,5 @@ Whether or not computations are provably correct by default """ -#proof = False +# proof = False proof = True diff --git a/src/sage/misc/rest_index_of_methods.py b/src/sage/misc/rest_index_of_methods.py index d1b102829c9..e3e29c593bf 100644 --- a/src/sage/misc/rest_index_of_methods.py +++ b/src/sage/misc/rest_index_of_methods.py @@ -166,7 +166,7 @@ def gen_rest_table_index(obj, names=None, sort=True, only_local_functions=True, # If input is a class/module, we list all its non-private and methods/functions if inspect.isclass(obj) or inspect.ismodule(obj): list_of_entries, names = list_of_subfunctions( - obj, only_local_functions=only_local_functions) + obj, only_local_functions=only_local_functions) else: list_of_entries = obj @@ -270,12 +270,12 @@ def list_of_subfunctions(root, only_local_functions=True): else: raise ValueError("'root' must be a module or a class.") - def local_filter(f,name): + def local_filter(f, name): if only_local_functions: if ismodule: return inspect.getmodule(root) == inspect.getmodule(f) else: - return not any(hasattr(s,name) for s in superclasses) + return not any(hasattr(s, name) for s in superclasses) else: return inspect.isclass(root) or not (f is gen_rest_table_index) @@ -288,13 +288,13 @@ def can_import(f): return True functions = {getattr(root, name): name for name, f in root.__dict__.items() if - (not name.startswith('_') and # private functions - can_import(f) and # unresolved lazy imports - not hasattr(f, 'issue_number') and # deprecated functions - not inspect.isclass(f) and # classes - callable(getattr(f, '__func__', f)) and # e.g. GenericGraph.graphics_array_defaults - local_filter(f, name)) # possibly filter imported functions - } + (not name.startswith('_') and # private functions + can_import(f) and # unresolved lazy imports + not hasattr(f, 'issue_number') and # deprecated functions + not inspect.isclass(f) and # classes + callable(getattr(f, '__func__', f)) and # e.g. GenericGraph.graphics_array_defaults + local_filter(f, name)) # possibly filter imported functions + } return list(functions.keys()), functions diff --git a/src/sage/misc/sage_input.py b/src/sage/misc/sage_input.py index 8f1a785e1c2..02e4fb78a23 100644 --- a/src/sage/misc/sage_input.py +++ b/src/sage/misc/sage_input.py @@ -2290,7 +2290,7 @@ def __repr__(self): """ return "{dict: {%s}}" % \ ', '.join([repr(key) + ':' + repr(val) - for key,val in self._sie_entries]) + for key, val in self._sie_entries]) def _sie_referenced(self): r""" @@ -2306,7 +2306,7 @@ def _sie_referenced(self): sage: sie._sie_referenced() [{atomic:1}, {atomic:2}, {atomic:3}, {atomic:'beguilement'}, {atomic:'legacy'}, {atomic:'passage'}] """ - return [k for k,v in self._sie_entries] + [v for k,v in self._sie_entries] + return [k for k, v in self._sie_entries] + [v for k, v in self._sie_entries] def _sie_format(self, sif): r""" @@ -2324,8 +2324,8 @@ def _sie_format(self, sif): sage: sie._sie_format(sif) ("{'carnivores':1, 'thinking':2, 'triumph':3}", 42) """ - return "{%s}" %\ - ', '.join(sif.format(k, 0)+':'+sif.format(v, 0) for k,v in self._sie_entries), _prec_atomic + return "{%s}" % ', '.join(sif.format(k, 0) + ':' + sif.format(v, 0) + for k, v in self._sie_entries), _prec_atomic class SIE_binary(SageInputExpression): @@ -2477,6 +2477,7 @@ def _sie_format(self, sif): rhs = sif.format(self._sie_operands[1], prec+1) return '%s%s%s' % (lhs, fop, rhs), prec + class SIE_unary(SageInputExpression): r""" This class represents an arithmetic expression with a unary operator @@ -2659,6 +2660,7 @@ def _sie_is_negation(self): """ return self._sie_op == '-' + class SIE_gens_constructor(SageInputExpression): r""" This class represents an expression that can create a \sage parent @@ -2707,7 +2709,7 @@ def __init__(self, sib, constr, gen_names, gens_syntax=None): super().__init__(sib) self._sie_constr = constr self._sie_gen_names = gen_names - self._sie_gens = None # will be overwritten from .parent_with_gens() + self._sie_gens = None # will be overwritten from .parent_with_gens() self._sie_gens_constr = gens_syntax self._sie_assign_gens = False self._sie_generated = False @@ -2888,6 +2890,7 @@ def _sie_format(self, sif): return self._sie_constr._sie_format(sif) + class SIE_gen(SageInputExpression): r""" This class represents a named generator of a parent with named @@ -3038,6 +3041,7 @@ def _sie_got_preferred(self, sif): """ return self._sie_get_varname(sif) == self._sie_preferred_varname + class SIE_import_name(SageInputExpression): r""" This class represents a name which has been imported from a module. @@ -3173,6 +3177,7 @@ def _sie_format(self, sif): rename) return name, _prec_atomic + class SIE_assign(SageInputExpression): r""" This class represents an assignment command. @@ -3278,6 +3283,7 @@ def _sie_format_statement(self, sif): """ return '%s = %s' % (sif.format(self._sie_lhs, 0), sif.format(self._sie_rhs, 0)) + class SageInputFormatter: r""" An instance of this class is used to keep track of variable names @@ -3441,6 +3447,7 @@ def get_name(self, name): else: return name + def verify_same(a, b): r""" Verify that two Sage values are the same. This is an extended equality @@ -3535,6 +3542,7 @@ def verify_si_answer(x, answer, preparse): else: verify_same(x, sage_eval(answer, preparse=preparse)) + class SageInputAnswer(tuple): r""" This class inherits from tuple, so it acts like a tuple when passed diff --git a/src/sage/misc/sagedoc_conf.py b/src/sage/misc/sagedoc_conf.py index 2cacfcf8327..d8e6c95e9a4 100644 --- a/src/sage/misc/sagedoc_conf.py +++ b/src/sage/misc/sagedoc_conf.py @@ -19,6 +19,7 @@ # The reST default role (used for this markup: `text`) to use for all documents. default_role = 'math' + def process_docstring_aliases(app, what, name, obj, options, docstringlines): """ Change the docstrings for aliases to point to the original object. @@ -27,6 +28,7 @@ def process_docstring_aliases(app, what, name, obj, options, docstringlines): if hasattr(obj, '__name__') and obj.__name__ != basename: docstringlines[:] = ['See :obj:`%s`.' % name] + def process_directives(app, what, name, obj, options, docstringlines): """ Remove 'nodetex' and other directives from the first line of any @@ -35,10 +37,11 @@ def process_directives(app, what, name, obj, options, docstringlines): if len(docstringlines) == 0: return first_line = docstringlines[0] - directives = [ d.lower() for d in first_line.split(',') ] + directives = [d.lower() for d in first_line.split(',')] if 'nodetex' in directives: docstringlines.pop(0) + def process_docstring_cython(app, what, name, obj, options, docstringlines): """ Remove Cython's filename and location embedding. @@ -48,10 +51,11 @@ def process_docstring_cython(app, what, name, obj, options, docstringlines): first_line = docstringlines[0] if first_line.startswith('File:') and '(starting at' in first_line: - #Remove the first two lines + # Remove the first two lines docstringlines.pop(0) docstringlines.pop(0) + def process_docstring_module_title(app, what, name, obj, options, docstringlines): """ Removes the first line from the beginning of the module's docstring. This @@ -60,20 +64,21 @@ def process_docstring_module_title(app, what, name, obj, options, docstringlines if what != "module": return - #Remove any additional blank lines at the beginning + # Remove any additional blank lines at the beginning title_removed = False while len(docstringlines) > 1 and not title_removed: if docstringlines[0].strip() != "": title_removed = True docstringlines.pop(0) - #Remove any additional blank lines at the beginning + # Remove any additional blank lines at the beginning while len(docstringlines) > 1: if docstringlines[0].strip() == "": docstringlines.pop(0) else: break + def process_dollars(app, what, name, obj, options, docstringlines): r""" Replace dollar signs with backticks. @@ -87,6 +92,7 @@ def process_dollars(app, what, name, obj, options, docstringlines): for i in range(len(lines)): docstringlines[i] = lines[i] + def process_inherited(app, what, name, obj, options, docstringlines): """ If we're including inherited members, omit their docstrings. @@ -110,6 +116,7 @@ def process_inherited(app, what, name, obj, options, docstringlines): for i in range(len(docstringlines)): docstringlines.pop() + def skip_TESTS_block(app, what, name, obj, options, docstringlines): """ Skip blocks labeled "TESTS:". @@ -127,6 +134,7 @@ def skip_TESTS_block(app, what, name, obj, options, docstringlines): while len(docstringlines) > len(lines): del docstringlines[len(lines)] + class SagemathTransform(Transform): """ Transform for code-blocks. @@ -147,6 +155,8 @@ def apply(self): node[:] = [nodes.Text(source)] # This is only used by sage.misc.sphinxify + + def setup(app): app.connect('autodoc-process-docstring', process_docstring_cython) app.connect('autodoc-process-docstring', process_directives) diff --git a/src/sage/misc/sageinspect.py b/src/sage/misc/sageinspect.py index fcd473c94e7..b684f0df810 100644 --- a/src/sage/misc/sageinspect.py +++ b/src/sage/misc/sageinspect.py @@ -965,21 +965,21 @@ def split_string(s, quot): a, b = split_string(s[3:], "'''") return "'''"+a+"'''", b.strip() if s.startswith("r'''"): - a,b = split_string(s[4:], "'''") + a, b = split_string(s[4:], "'''") return "r'''"+a+"'''", b.strip() # 2. s is a single-quoted string if s.startswith('"'): - a,b = split_string(s[1:], '"') + a, b = split_string(s[1:], '"') return '"'+a+'"', b.strip() if s.startswith("'"): - a,b = split_string(s[1:], "'") + a, b = split_string(s[1:], "'") return "'"+a+"'", b.strip() if s.startswith('r"'): - a,b = split_string(s[2:], '"') + a, b = split_string(s[2:], '"') return 'r"'+a+'"', b.strip() if s.startswith("r'"): - a,b = split_string(s[2:], "'") + a, b = split_string(s[2:], "'") return "r'"+a+"'", b.strip() # 3. s is not a string @@ -1000,7 +1000,7 @@ def split_string(s, quot): elif start == '#': linebreak = s.index(os.linesep) if linebreak == -1: - return '','' + return '', '' return '', s[linebreak:].strip() else: M = __identifier_re.search(s) @@ -1018,7 +1018,7 @@ def split_string(s, quot): elif s.startswith(stop): out.append(stop) return ''.join(out), s[1:].strip() - raise SyntaxError("Syntactical group starting with %s did not end with %s" % (repr(start),repr(stop))) + raise SyntaxError("Syntactical group starting with %s did not end with %s" % (repr(start), repr(stop))) def _sage_getargspec_from_ast(source): @@ -1183,7 +1183,7 @@ def _sage_getargspec_cython(source): while (i < l): unit = cy_units[i] if expect_default: - if unit in ('=','*',','): + if unit in ('=', '*', ','): raise SyntaxError("Definition of a default argument expected") while unit != ',': py_units.append(unit) @@ -1224,7 +1224,7 @@ def _sage_getargspec_cython(source): # Is "name" part of a type definition? # If it is the last identifier before '=' or ',', # then it *is* a variable name, - if i == l or cy_units[i] in ('=',','): + if i == l or cy_units[i] in ('=', ','): if nb_stars == 0: py_units.append(name) elif nb_stars == 1: @@ -1329,12 +1329,12 @@ def sage_getfile(obj): if isclassinstance(obj): if isinstance(obj, functools.partial): return sage_getfile(obj.func) - return sage_getfile(obj.__class__) #inspect.getabsfile(obj.__class__) + return sage_getfile(obj.__class__) # inspect.getabsfile(obj.__class__) # No go? fall back to inspect. try: sourcefile = inspect.getabsfile(obj) - except TypeError: # this happens for Python builtins + except TypeError: # this happens for Python builtins return '' for suffix in import_machinery.EXTENSION_SUFFIXES: if sourcefile.endswith(suffix): @@ -1625,7 +1625,7 @@ def foo(x, a='\')"', b={not (2+1==3):'bar'}): return except (TypeError, AttributeError): pass if isclassinstance(obj): - if hasattr(obj, '_sage_src_'): #it may be a decorator! + if hasattr(obj, '_sage_src_'): # it may be a decorator! source = sage_getsource(obj) try: # we try to find the definition and parse it by @@ -1653,7 +1653,7 @@ def foo(x, a='\')"', b={not (2+1==3):'bar'}): return # embedded in the docstring) try: source = sage_getsource(obj) - except TypeError: # happens for Python builtins + except TypeError: # happens for Python builtins source = '' if source: return inspect.FullArgSpec(*_sage_getargspec_cython(source)) @@ -1666,11 +1666,11 @@ def foo(x, a='\')"', b={not (2+1==3):'bar'}): return except AttributeError: try: args, varargs, varkw = inspect.getargs(func_obj) - except TypeError: # arg is not a code object + except TypeError: # arg is not a code object # The above "hopefully" was wishful thinking: try: return inspect.FullArgSpec(*_sage_getargspec_cython(sage_getsource(obj))) - except TypeError: # This happens for Python builtins + except TypeError: # This happens for Python builtins # The best we can do is to return a generic argspec args = [] varargs = 'args' @@ -1990,7 +1990,7 @@ def sage_getdoc_original(obj): else: typ = type(obj) - s,argspec = _extract_embedded_signature(_sage_getdoc_unformatted(obj), typ.__name__) + s, argspec = _extract_embedded_signature(_sage_getdoc_unformatted(obj), typ.__name__) if s: pos = _extract_embedded_position(s) if pos is not None: @@ -2216,7 +2216,7 @@ class ParentMethods: pmatch = pat.match # fperez - fix: sometimes, co_firstlineno can give a number larger than # the length of lines, which causes an error. Safeguard against that. - lnum = min(obj.co_firstlineno,len(lines))-1 + lnum = min(obj.co_firstlineno, len(lines)) - 1 while lnum > 0: if pmatch(lines[lnum]): break diff --git a/src/sage/misc/sphinxify.py b/src/sage/misc/sphinxify.py index b33b66c673a..66a42476669 100644 --- a/src/sage/misc/sphinxify.py +++ b/src/sage/misc/sphinxify.py @@ -82,7 +82,7 @@ def sphinxify(docstring, format='html'): with open(rst_name, 'w') as filed: filed.write(docstring) - confdir = os.path.join(srcdir, 'en' , 'introspect') + confdir = os.path.join(srcdir, 'en', 'introspect') os.makedirs(confdir) with open(os.path.join(confdir, 'conf.py'), 'w') as filed: filed.write(r""" diff --git a/src/sage/misc/superseded.py b/src/sage/misc/superseded.py index f646c24e485..9bba30e6d83 100644 --- a/src/sage/misc/superseded.py +++ b/src/sage/misc/superseded.py @@ -97,6 +97,7 @@ def deprecation(issue_number, message, stacklevel=4): """ warning(issue_number, message, DeprecationWarning, stacklevel) + def deprecation_cython(issue_number, message, stacklevel=3): r""" Issue a deprecation warning -- for use in cython functions @@ -135,6 +136,7 @@ def deprecation_cython(issue_number, message, stacklevel=3): """ warning(issue_number, message, DeprecationWarning, stacklevel) + def warning(issue_number, message, warning_class=Warning, stacklevel=3): r""" Issue a warning. diff --git a/src/sage/misc/temporary_file.py b/src/sage/misc/temporary_file.py index fecf5867f89..1206c9c1605 100644 --- a/src/sage/misc/temporary_file.py +++ b/src/sage/misc/temporary_file.py @@ -413,6 +413,8 @@ def __exit__(self, exc_type, exc_val, exc_tb): ################################################################# # write to a temporary directory and move it in place ################################################################# + + class atomic_dir: """ Write to a given directory using a temporary directory and then rename it @@ -524,6 +526,8 @@ def __exit__(self, exc_type, exc_val, exc_tb): _spyx_tmp = None + + def spyx_tmp(): r""" The temporary directory used to store pyx files. diff --git a/src/sage/misc/test_class_pickling.py b/src/sage/misc/test_class_pickling.py index f1074af85cb..bcc58d3a396 100644 --- a/src/sage/misc/test_class_pickling.py +++ b/src/sage/misc/test_class_pickling.py @@ -33,6 +33,7 @@ def metaclass(name, bases): result.reduce_args = (name, bases) return result + class Metaclass(type): """ This metaclass illustrates the customization of how a class is pickled. diff --git a/src/sage/misc/test_nested_class.py b/src/sage/misc/test_nested_class.py index 918acc30e11..bd858529e79 100644 --- a/src/sage/misc/test_nested_class.py +++ b/src/sage/misc/test_nested_class.py @@ -38,12 +38,12 @@ sage: TestSuite(P).run() """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2009 Nicolas M. Thiery # # Distributed under the terms of the GNU General Public License (GPL) # http://www.gnu.org/licenses/ -#****************************************************************************** +# ****************************************************************************** __all__ = [] # Don't document any parents diff --git a/src/sage/misc/unknown.py b/src/sage/misc/unknown.py index b87a3e67506..c08b2737e69 100644 --- a/src/sage/misc/unknown.py +++ b/src/sage/misc/unknown.py @@ -83,6 +83,7 @@ from sage.structure.unique_representation import UniqueRepresentation from sage.structure.richcmp import richcmp_method, rich_to_bool + class UnknownError(TypeError): """ Raised whenever :class:`Unknown` is used in a boolean operation. @@ -96,6 +97,7 @@ class UnknownError(TypeError): """ pass + @richcmp_method class UnknownClass(UniqueRepresentation): """ diff --git a/src/sage/misc/verbose.py b/src/sage/misc/verbose.py index 37a86854358..09b61c8fc50 100644 --- a/src/sage/misc/verbose.py +++ b/src/sage/misc/verbose.py @@ -89,7 +89,7 @@ Functions ========= """ -#***************************************************************************** +# ***************************************************************************** # Copyright (C) 2006, 2007 William Stein # Copyright (C) 2006 Gonzalo Tornaria # Copyright (C) 2008 John H. Palmieri @@ -102,7 +102,7 @@ # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # http://www.gnu.org/licenses/ -#***************************************************************************** +# ***************************************************************************** import sys import os