Skip to content

Commit

Permalink
Trac #13255: Replace some deprecated python functions in sage/misc
Browse files Browse the repository at this point in the history
Moving forward to Python 3.

Execute
{{{
2to3 -f has_key -f except -f idioms -f ne -f print -f raise
}}}
for each *.py (and *.pyx) in sage/misc.

URL: http://trac.sagemath.org/13255
Reported by: aapitzsch
Ticket author(s): André Apitzsch
Reviewer(s): Wilfried Luebbe
  • Loading branch information
Release Manager authored and vbraun committed Apr 19, 2014
2 parents 6aac28f + 0c7d2ff commit 2cbddb4
Show file tree
Hide file tree
Showing 44 changed files with 285 additions and 283 deletions.
2 changes: 1 addition & 1 deletion src/sage/misc/abstract_method.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ def _sage_src_lines_(self):
sage: src[0]
'def banner():\n'
sage: lines
79
78
"""
from sage.misc.sageinspect import sage_getsourcelines
return sage_getsourcelines(self._f)
Expand Down
4 changes: 2 additions & 2 deletions src/sage/misc/attached_files.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ def modified_file_iterator():
for filename in attached.keys():
old_tm = attached[filename]
if not os.path.exists(filename):
print '### detaching file {0} because it does not exist (deleted?) ###'.format(filename)
print('### detaching file {0} because it does not exist (deleted?) ###'.format(filename))
detach(filename)
continue
new_tm = os.path.getmtime(filename)
Expand Down Expand Up @@ -579,6 +579,6 @@ def reload_attached_files_if_modified():
timestr = time.strftime('%T', mtime)
from sage.libs.readline import interleaved_output
with interleaved_output():
print '### reloading attached file {0} modified at {1} ###'.format(basename, timestr)
print('### reloading attached file {0} modified at {1} ###'.format(basename, timestr))
code = load_wrap(filename, attach=True)
get_ipython().run_cell(code)
10 changes: 4 additions & 6 deletions src/sage/misc/banner.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
# http://www.gnu.org/licenses/
#*****************************************************************************


from sage.env import SAGE_VERSION, SAGE_DATE, SAGE_SRC

def version(clone = False):
Expand Down Expand Up @@ -97,7 +96,7 @@ def banner():
│ Type "help()" for help. │
...
"""
print banner_text()
print(banner_text())


def version_dict():
Expand Down Expand Up @@ -207,8 +206,7 @@ def require_version(major, minor=0, tiny=0, prerelease=False,
return True
else:
if print_message:
print "This code requires at least version",
print "%g" % (major + 0.1 * minor + 0.01 * tiny,),
print "of Sage to run correctly."
print "You are running version %s." % SAGE_VERSION
print("This code requires at least version {} of Sage to run correctly.".
format(major + 0.1 * minor + 0.01 * tiny))
print("You are running version {}.".format(SAGE_VERSION))
return False
10 changes: 5 additions & 5 deletions src/sage/misc/benchmark.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ def benchmark(n=-1):
return v, cputime(t)

if n != -1:
print "Running benchmark %s"%n
print("Running benchmark {}".format(n))
try:
desc, t = eval("bench%s()"%n)
desc, t = eval("bench{}()".format(n))
except NameError:
raise RuntimeError("no benchmark %s"%n)
print desc
print "Time: %s seconds"%t
raise RuntimeError("no benchmark {}".format(n))
print(desc)
print("Time: {} seconds".format(t))
return (n, t, desc)

t = cputime()
Expand Down
8 changes: 4 additions & 4 deletions src/sage/misc/bug.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def bug():
AUTHOR: David Joyner (2006-05)
"""
print "We will now create a bug report in a standard format."
print("We will now create a bug report in a standard format.")
import os
import time
report = """
Expand Down Expand Up @@ -59,7 +59,7 @@ def bug():
comments = raw_input("Comments or suggestions (one line)? ")
report = report + comments + "\n"
except (EOFError, KeyboardInterrupt):
print "Creation of bug report cancelled."
print "Type bug() to create the report again."
print report
print("Creation of bug report cancelled.")
print("Type bug() to create the report again.")
print(report)

2 changes: 1 addition & 1 deletion src/sage/misc/c3.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -230,5 +230,5 @@ cpdef list C3_algorithm(object start, str bases, str attribute, bint proper):
break
if not next_item_found:
# No head is available
raise ValueError, "Can not merge the items %s."%', '.join([repr(head) for head in heads])
raise ValueError("Can not merge the items {}.".format(', '.join([repr(head) for head in heads])))
return out
34 changes: 18 additions & 16 deletions src/sage/misc/cachefunc.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1745,9 +1745,9 @@ cdef class CachedMethodCallerNoArgs(CachedFunction):
if hasattr(inst, cachename):
# This is for data that are pickled in an old format
CACHE = getattr(inst, cachename)
if len(CACHE)>1:
raise TypeError, "Apparently you are opening a pickle in which '%s' was a method accepting arguments"%name
if len(CACHE)==1:
if len(CACHE) > 1:
raise TypeError("Apparently you are opening a pickle in which '{}' was a method accepting arguments".format(name))
if len(CACHE) == 1:
self.cache = CACHE.values()[0]
else:
self.cache = cache
Expand Down Expand Up @@ -2598,7 +2598,9 @@ cdef class CachedInParentMethod(CachedMethod):
except AttributeError:
pass
if not hasattr(P,'__cached_methods'):
raise TypeError, "The parent of this element does not allow attribute assignment\n and does not descend from the Parent base class.\n Can not use CachedInParentMethod."
raise TypeError("The parent of this element does not allow attribute assignment\n" +
" and does not descend from the Parent base class.\n" +
" Can not use CachedInParentMethod.")
if P.__cached_methods is None:
P.__cached_methods = {}
return (<dict>P.__cached_methods).setdefault(self._cache_name, {})
Expand Down Expand Up @@ -3143,35 +3145,35 @@ class ClearCacheOnPickle(object):
def clear_list(T):
L = []
for x in T:
if isinstance(x,list):
if isinstance(x, list):
L.append(clear_list(x))
elif isinstance(x,tuple):
elif isinstance(x, tuple):
L.append(clear_tuple(x))
elif isinstance(x,dict):
elif isinstance(x, dict):
L.append(clear_dict(x))
elif not isinstance(x,CachedFunction):
elif not isinstance(x, CachedFunction):
L.append(x)
return L
def clear_tuple(T):
return tuple(clear_list(T))
def clear_dict(T):
D = {}
for key,value in T.iteritems():
if not ((type(key) == str and key[0:8] == '_cache__') or
isinstance(value,CachedFunction)):
if isinstance(value,list):
if not ((isinstance(key, str) and key[0:8] == '_cache__') or
isinstance(value, CachedFunction)):
if isinstance(value, list):
D[key] = clear_list(value)
elif isinstance(value,tuple):
elif isinstance(value, tuple):
D[key] = clear_tuple(value)
elif isinstance(value,dict):
elif isinstance(value, dict):
D[key] = clear_dict(value)
else:
D[key] = value
return D
if isinstance(OrigState,tuple):
if isinstance(OrigState, tuple):
return clear_tuple(OrigState)
if isinstance(OrigState,list):
if isinstance(OrigState, list):
return clear_list(OrigState)
if isinstance(OrigState,dict):
if isinstance(OrigState, dict):
return clear_dict(OrigState)
return OrigState
2 changes: 1 addition & 1 deletion src/sage/misc/citation.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def get_systems(cmd):
import cProfile, pstats, re

if not isinstance(cmd, basestring):
raise TypeError, "command must be a string"
raise TypeError("command must be a string")

cmd = preparse(cmd)

Expand Down
2 changes: 1 addition & 1 deletion src/sage/misc/classcall_metaclass.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -320,7 +320,7 @@ cdef class ClasscallMetaclass(NestedClassMetaclass):
... __metaclass__ = ClasscallMetaclass
... @staticmethod
... def __classcall__(cls):
... raise ValueError, "Calling classcall"
... raise ValueError("Calling classcall")
sage: Exc()
Traceback (most recent call last):
...
Expand Down
8 changes: 4 additions & 4 deletions src/sage/misc/cython.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,7 +490,7 @@ def cython(filename, verbose=False, compile_message=False,
if os.system(cmd):
log = open('%s/log'%build_dir).read()
err = subtract_from_line_numbers(open('%s/err'%build_dir).read(), offset)
raise RuntimeError("Error converting %s to C:\n%s\n%s"%(filename, log, err))
raise RuntimeError("Error converting {} to C:\n{}\n{}".format(filename, log, err))

if language=='c++':
os.system("cd '%s' && mv '%s.c' '%s.cpp'"%(build_dir,name,name))
Expand Down Expand Up @@ -533,14 +533,14 @@ def cython(filename, verbose=False, compile_message=False,
if os.system(cmd):
log = open('%s/log'%build_dir).read()
err = open('%s/err'%build_dir).read()
raise RuntimeError("Error compiling %s:\n%s\n%s"%(filename, log, err))
raise RuntimeError("Error compiling {}:\n{}\n{}".format(filename, log, err))

# Move from lib directory.
cmd = 'mv %s/build/lib.*/* %s'%(build_dir, build_dir)
if verbose:
print(cmd)
if os.system(cmd):
raise RuntimeError("Error copying extension module for %s"%filename)
raise RuntimeError("Error copying extension module for {}".format(filename))

if create_local_so_file:
# Copy from lib directory into local directory
Expand All @@ -550,7 +550,7 @@ def cython(filename, verbose=False, compile_message=False,
libext = 'dll'
cmd = 'cp %s/%s.%s %s'%(build_dir, name, libext, os.path.abspath(os.curdir))
if os.system(cmd):
raise RuntimeError("Error making local copy of shared object library for %s"%filename)
raise RuntimeError("Error making local copy of shared object library for {}".format(filename))

return name, build_dir

Expand Down
6 changes: 3 additions & 3 deletions src/sage/misc/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,9 @@ def load_db(x):
"""
fn = PATH + x.filename()
if os.path.exists(fn + ".bz2"):
print "Loading %s from %s."%(x,x.filename())
os.system("bunzip2 -f -k %s"%(fn + ".bz2"))
o=open(fn,"r")
print("Loading {} from {}.".format(x, x.filename()))
os.system("bunzip2 -f -k {}".format(fn + ".bz2"))
o = open(fn, "r")
x = cPickle.load(o)
os.remove(fn)
return x
Expand Down
3 changes: 1 addition & 2 deletions src/sage/misc/derivative.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def derivative_parse(args):
# process iteration count
count = int(arg)
if count < 0:
raise ValueError, "derivative counts must be non-negative"
raise ValueError("derivative counts must be non-negative")
if not got_var:
var = None
for i from 0 <= i < count:
Expand All @@ -177,7 +177,6 @@ def derivative_parse(args):
return output



def multi_derivative(F, args):
r"""
Calls F._derivative(var) for a sequence of variables specified by args.
Expand Down
15 changes: 7 additions & 8 deletions src/sage/misc/dev_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -544,9 +544,9 @@ def import_statements(*objects, **options):
modules = set()
for o in obj:
modules.update(find_object_modules(o))
print "# **Warning**: distinct objects with name '%s' in:"%name
print("# **Warning**: distinct objects with name '{}' in:".format(name))
for module_name in modules:
print "# - %s"%module_name
print("# - {}".format(module_name))

# choose a random object among the potentially enormous list of
# objects we get from "name"
Expand Down Expand Up @@ -576,13 +576,13 @@ def import_statements(*objects, **options):
del modules['__main__']

if not modules:
raise ValueError("no import statement found for '%s'."%obj)
raise ValueError("no import statement found for '{}'.".format(obj))

if len(modules) == 1: # the module is well defined
module_name, obj_names = modules.items()[0]
if name is None:
if verbose and len(obj_names) > 1:
print "# ** Warning **: several names for that object: %s"%', '.join(sorted(obj_names))
print("# ** Warning **: several names for that object: {}".format(', '.join(sorted(obj_names))))
name = alias = obj_names[0]
elif name in modules[module_name]:
alias = name
Expand Down Expand Up @@ -630,12 +630,11 @@ def import_statements(*objects, **options):

not_all_modules = [module_name for module_name in modules if not '.all_' in module_name and not module_name.endswith('.all')]
if not(not_all_modules):
print "# ** Warning **: the object %s is only defined in .all modules"%obj
print("# ** Warning **: the object {} is only defined in .all modules".format(obj))
module_name = modules.keys()[0]

else:
if len(not_all_modules) > 1:
print "# ** Warning **: several modules for the object %s: %s"%(obj, ', '.join(modules.keys()))
print("# ** Warning **: several modules for the object {}: {}".format(obj, ', '.join(modules.keys())))
module_name = not_all_modules[0]

# 3. Now that we found the module, we fix the problem of the alias
Expand All @@ -660,5 +659,5 @@ def import_statements(*objects, **options):
if answer_as_str:
return '\n'.join(res)
else:
print '\n'.join(res)
print('\n'.join(res))

2 changes: 1 addition & 1 deletion src/sage/misc/displayhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ def __call__(self, obj):
return
s = self.try_format_obj(obj)
if s is not None:
print s
print(s)
__builtin__._ = obj
else:
self.oldhook(obj)
Expand Down

0 comments on commit 2cbddb4

Please sign in to comment.