Ran python-modernize on examples, doc, and utils.

This commit is contained in:
danyeaw 2017-04-29 22:26:39 -04:00
parent e919f92040
commit c2fb84888e
13 changed files with 114 additions and 87 deletions

View File

@ -8,6 +8,7 @@
# All configuration values have a default; values that are commented out
# serve to show the default.
from __future__ import absolute_import
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,

View File

@ -3,6 +3,8 @@
"""This script list classes and optionally attributes from UML model
created with Gaphor."""
from __future__ import absolute_import
from __future__ import print_function
import sys
import optparse
@ -42,10 +44,10 @@ file_manager.load(model)
#Find all classes using factory select.
for cls in element_factory.select(lambda e: e.isKindOf(UML.Class)):
print 'Found class %s' % cls.name
print('Found class %s' % cls.name)
if options.attrs:
for attr in cls.ownedAttribute:
print ' Attribute: %s' % attr.name
print(' Attribute: %s' % attr.name)

View File

@ -7,6 +7,8 @@
#
# Arjan Molenaar.
from __future__ import absolute_import
from __future__ import print_function
import sys
sys.path.append("..")
@ -17,10 +19,10 @@ done = [object]
def print_vars(cls):
global done
done.append(cls)
print cls.__name__ + ":"
print(cls.__name__ + ":")
dict = cls.__dict__
for key in dict.keys():
print "\t" + key + ":", str(dict[key])
print("\t" + key + ":", str(dict[key]))
for base in cls.__bases__:
if base not in done:
print_vars(base)
@ -32,5 +34,5 @@ if args:
cls = eval(args[0])
print_vars(cls)
else:
print "Usage: " + sys.argv[0] + " <UML class name>"
print("Usage: " + sys.argv[0] + " <UML class name>")
sys.exit(1)

View File

@ -4,10 +4,12 @@
Generate .mo files from po files.
"""
from __future__ import absolute_import
from __future__ import print_function
from distutils.core import Command
from distutils.dep_util import newer
import os.path
import msgfmt
from . import msgfmt
class build_mo(Command):
@ -50,10 +52,10 @@ class build_mo(Command):
self.mkpath(outdir)
outfile = os.path.join(outdir, 'gaphor.mo')
if self.force or newer(pofile, outfile):
print 'converting %s -> %s' % (pofile, outfile)
print('converting %s -> %s' % (pofile, outfile))
msgfmt.make(pofile, outfile)
else:
print 'not converting %s (output up-to-date)' % pofile
print('not converting %s (output up-to-date)' % pofile)
from distutils.command.build import build
build.sub_commands.append(('build_mo', None))

View File

@ -5,11 +5,13 @@ Build a PO template (for i18n) and update the .po files to reflect
the last changes.
"""
from __future__ import absolute_import
from __future__ import print_function
import os.path
import sys
from distutils.core import Command
import pygettext
from . import pygettext
# from pygettext.main():
@ -101,7 +103,7 @@ class build_pot(Command):
elif self.style == 'solaris':
options.locationstyle = self.SOLARIS
else:
raise SystemExit, 'Invalid value for --style: %s' % self.style
raise SystemExit('Invalid value for --style: %s' % self.style)
if not self.output:
self.output = self.distribution.get_name() + '.pot'
if not self.output_dir:
@ -115,7 +117,7 @@ class build_pot(Command):
options.toexclude = fp.readlines()
fp.close()
except IOError:
raise SystemExit, "Can't read --exclude-file: %s" % self.exclude_file
raise SystemExit("Can't read --exclude-file: %s" % self.exclude_file)
# skip: self.no_docstrings
if self.all_linguas:
self.all_linguas = self.all_linguas.split(',')
@ -148,22 +150,22 @@ class build_pot(Command):
source_files = []
for p in self.packages:
pathlist = p.split('.')
path = apply(os.path.join, pathlist)
path = os.path.join(*pathlist)
source_files.extend(glob.glob(os.path.join(path, '*.py')))
# slurp through all the files
eater = pygettext.TokenEater(self.options)
for filename in source_files:
if self.verbose:
print 'Working on %s' % filename
print('Working on %s' % filename)
fp = open(filename)
try:
eater.set_filename(filename)
try:
tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError, e:
print '%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1])
except tokenize.TokenError as e:
print('%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1]))
finally:
fp.close()

View File

@ -6,6 +6,8 @@ into gaphor/UML/uml2.py.
Also a distutils tool, build_uml, is provided.
"""
from __future__ import absolute_import
from __future__ import print_function
import os.path
from distutils.core import Command
from distutils.dep_util import newer
@ -49,12 +51,12 @@ class build_uml(Command):
if self.force or newer(model, outfile) \
or newer(overrides, outfile) \
or newer(gen, outfile):
print 'generating %s from %s...' % (py_model, model)
print ' (warnings can be ignored)'
import gen_uml
print('generating %s from %s...' % (py_model, model))
print(' (warnings can be ignored)')
from . import gen_uml
gen_uml.generate(model, outfile, overrides)
else:
print 'not generating %s (up-to-date)' % py_model
print('not generating %s (up-to-date)' % py_model)
byte_compile([outfile])
# vim:sw=4:et

View File

@ -16,10 +16,13 @@ Also a distutils tool, build_uml, is provided.
# Recreate the model using some very dynamic class, so we can set all
# attributes and traverse them to generate the data model.
from __future__ import absolute_import
from __future__ import print_function
import sys
import override
from . import override
from gaphor.storage.parser import parse, base, element
from six.moves import map
header = """# This file is generated by build_uml.py. DO NOT EDIT!
@ -118,7 +121,7 @@ class Writer:
if type is None:
raise ValueError('ERROR! type is not specified for property %s.%s' % (a.class_name, a.name))
print a.class_name, a.name, 'type is', type
print(a.class_name, a.name, 'type is', type)
if type.lower() == 'boolean':
# FixMe: Should this be a boolean or an integer?
# Integer is save and compattable with python2.2.
@ -154,12 +157,12 @@ class Writer:
elif eval(a.isDerived or '0'):
msg('ignoring derived attribute %s.%s: no definition' % (a.class_name, a.name))
elif type.endswith('Kind') or type.endswith('Sort'):
e = filter(lambda e: e['name'] == type, enumerations.values())[0]
e = filter(lambda e: e['name'] == type, list(enumerations.values()))[0]
self.write_property("%s.%s" % (a.class_name, a.name),
"enumeration('%s', %s, '%s')" % (a.name, e.enumerates, default or e.enumerates[0]))
else:
if params:
attribute = "attribute('%s', %s, %s)" % (a.name, type, ', '.join(map('='.join, params.items())))
attribute = "attribute('%s', %s, %s)" % (a.name, type, ', '.join(map('='.join, list(params.items()))))
else:
attribute = "attribute('%s', %s)" % (a.name, type)
self.write_property("%s.%s" % (a.class_name, a.name), attribute)
@ -430,14 +433,14 @@ def generate(filename, outfile=None, overridesfile=None):
instSpec = all_elements[c.appliedStereotype[0]]
sType = all_elements[instSpec.classifier[0]]
c.stereotypeName = sType.name
print " class '%s' has been stereotyped as '%s'" % (c.name, c.stereotypeName)
print(" class '%s' has been stereotyped as '%s'" % (c.name, c.stereotypeName))
writer.write("# class '%s' has been stereotyped as '%s'\n" % (c.name, c.stereotypeName))
# c.written = True
def tag_children(me):
for child in me.specialization:
child.stereotypeName = sType.name
print " class '%s' has been stereotyped as '%s' too" % (child.name, child.stereotypeName)
print(" class '%s' has been stereotyped as '%s' too" % (child.name, child.stereotypeName))
writer.write("# class '%s' has been stereotyped as '%s' too\n" % (child.name, child.stereotypeName))
# child.written = True
tag_children(child)
@ -455,7 +458,7 @@ def generate(filename, outfile=None, overridesfile=None):
# create attributes and enumerations
derivedattributes = {}
for c in filter(lambda c: c not in ignored_classes, classes.values()):
for c in [c for c in list(classes.values()) if c not in ignored_classes]:
for p in c.get('ownedAttribute') or []:
a = properties.get(p)
# set class_name, since write_attribute depends on it
@ -529,7 +532,7 @@ def generate(filename, outfile=None, overridesfile=None):
writer.write_redefine(r)
# create operations
for c in filter(lambda c: c not in ignored_classes, classes.values()):
for c in [c for c in list(classes.values()) if c not in ignored_classes]:
for p in c.get('ownedOperation') or ():
o = operations.get(p)
o.class_name = c['name']

View File

@ -1,3 +1,4 @@
from __future__ import absolute_import
from setuptools.command.install_lib import install_lib as _install_lib

View File

@ -25,6 +25,8 @@ Options:
Display version information and exit.
"""
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
import getopt
@ -38,9 +40,9 @@ MESSAGES = {}
def usage(code, msg=''):
print >> sys.stderr, __doc__
print(__doc__, file=sys.stderr)
if msg:
print >> sys.stderr, msg
print(msg, file=sys.stderr)
sys.exit(code)
@ -56,7 +58,7 @@ def add(id, str, fuzzy):
def generate():
"Return the generated output."
global MESSAGES
keys = MESSAGES.keys()
keys = list(MESSAGES.keys())
# the keys are sorted in the .mo file
keys.sort()
offsets = []
@ -83,7 +85,7 @@ def generate():
voffsets += [l2, o2+valuestart]
offsets = koffsets + voffsets
output = struct.pack("Iiiiiii",
0x950412deL, # Magic
0x950412de, # Magic
0, # Version
len(keys), # # of entries
7*4, # start of key index
@ -110,8 +112,8 @@ def make(filename, outfile):
try:
lines = open(infile).readlines()
except IOError, msg:
print >> sys.stderr, msg
except IOError as msg:
print(msg, file=sys.stderr)
sys.exit(1)
section = None
@ -154,9 +156,9 @@ def make(filename, outfile):
elif section == STR:
msgstr += l
else:
print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \
'before:'
print >> sys.stderr, l
print('Syntax error on %s:%d' % (infile, lno), \
'before:', file=sys.stderr)
print(l, file=sys.stderr)
sys.exit(1)
# Add last entry
if section == STR:
@ -167,8 +169,8 @@ def make(filename, outfile):
try:
open(outfile,"wb").write(output)
except IOError,msg:
print >> sys.stderr, msg
except IOError as msg:
print(msg, file=sys.stderr)
@ -176,7 +178,7 @@ def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'hVo:',
['help', 'version', 'output-file='])
except getopt.error, msg:
except getopt.error as msg:
usage(1, msg)
outfile = None
@ -185,14 +187,14 @@ def main():
if opt in ('-h', '--help'):
usage(0)
elif opt in ('-V', '--version'):
print >> sys.stderr, "msgfmt.py", __version__
print("msgfmt.py", __version__, file=sys.stderr)
sys.exit(0)
elif opt in ('-o', '--output-file'):
outfile = arg
# do it
if not args:
print >> sys.stderr, 'No input file given'
print >> sys.stderr, "Try `msgfmt --help' for more information."
print('No input file given', file=sys.stderr)
print("Try `msgfmt --help' for more information.", file=sys.stderr)
return
for filename in args:

View File

@ -6,6 +6,8 @@ do its job correctly.
This is a simple rip-off of the override script used in PyGTK.
"""
from __future__ import absolute_import
from __future__ import print_function
import string
@ -64,7 +66,7 @@ class Overrides:
elif words[0] == 'comment':
pass # ignore comments
else:
print "Unknown word: '%s', line %d"(words[0], startline)
print("Unknown word: '%s', line %d"(words[0], startline))
raise SystemExit
def has_override(self, key):

View File

@ -14,6 +14,10 @@
#
# for selftesting
from __future__ import absolute_import
from __future__ import print_function
from six.moves import range
from functools import reduce
try:
import fintl
_ = fintl.gettext
@ -195,9 +199,9 @@ msgstr ""
def usage(code, msg=''):
print >> sys.stderr, __doc__ % globals()
print(__doc__ % globals(), file=sys.stderr)
if msg:
print >> sys.stderr, msg
print(msg, file=sys.stderr)
sys.exit(code)
@ -265,7 +269,7 @@ def _visit_pyfiles(list, dirname, names):
""" Helper for getFilesForName().
"""
# get extension for python source files
if not globals().has_key('_py_ext'):
if '_py_ext' not in globals():
import imp
global _py_ext
_py_ext = [triple[0] for triple in imp.get_suffixes() if triple[2] == imp.PY_SOURCE][0]
@ -426,8 +430,8 @@ class TokenEater:
elif ttype not in [tokenize.COMMENT, token.INDENT, token.DEDENT,
token.NEWLINE, tokenize.NL]:
# warn if we see anything else than STRING or whitespace
print >>sys.stderr, _('*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"') % {
'token': tstring, 'file': self.__curfile, 'lineno': self.__lineno}
print(_('*** %(file)s:%(lineno)s: Seen unexpected token "%(token)s"') % {
'token': tstring, 'file': self.__curfile, 'lineno': self.__lineno}, file=sys.stderr)
self.__state = self.__waiting
def __addentry(self, msg, lineno=None, isdocstring=0):
@ -446,15 +450,15 @@ class TokenEater:
timestamp = time.ctime(time.time())
# The time stamp in the header doesn't have the same format as that
# generated by xgettext...
print >> fp, pot_header % {'time': timestamp, 'version': __version__}
print(pot_header % {'time': timestamp, 'version': __version__}, file=fp)
# Sort the entries. First sort each particular entry's keys, then
# sort all the entries by their first item.
reverse = {}
for k, v in self.__messages.items():
keys = v.keys()
keys = list(v.keys())
keys.sort()
reverse.setdefault(tuple(keys), []).append((k, v))
rkeys = reverse.keys()
rkeys = list(reverse.keys())
rkeys.sort()
for rkey in rkeys:
rentries = reverse[rkey]
@ -464,12 +468,12 @@ class TokenEater:
# If the entry was gleaned out of a docstring, then add a
# comment stating so. This is to aid translators who may wish
# to skip translating some unimportant docstrings.
if reduce(operator.__add__, v.values()):
if reduce(operator.__add__, list(v.values())):
isdocstring = 1
# k is the message string, v is a dictionary-set of (filename,
# lineno) tuples. We want to sort the entries in v first by
# file name and then by line number.
v = v.keys()
v = list(v.keys())
v.sort()
if not options.writelocations:
pass
@ -477,8 +481,8 @@ class TokenEater:
elif options.locationstyle == options.SOLARIS:
for filename, lineno in v:
d = {'filename': filename, 'lineno': lineno}
print >>fp, _(
'# File: %(filename)s, line: %(lineno)d') % d
print(_(
'# File: %(filename)s, line: %(lineno)d') % d, file=fp)
elif options.locationstyle == options.GNU:
# fit as many locations on one line, as long as the
# resulting line length doesn't exceeds 'options.width'
@ -489,14 +493,14 @@ class TokenEater:
if len(locline) + len(s) <= options.width:
locline = locline + s
else:
print >> fp, locline
print(locline, file=fp)
locline = "#:" + s
if len(locline) > 2:
print >> fp, locline
print(locline, file=fp)
if isdocstring:
print >> fp, '#, docstring'
print >> fp, 'msgid', normalize(k)
print >> fp, 'msgstr ""\n'
print('#, docstring', file=fp)
print('msgid', normalize(k), file=fp)
print('msgstr ""\n', file=fp)
@ -512,7 +516,7 @@ def main():
'style=', 'verbose', 'version', 'width=', 'exclude-file=',
'docstrings', 'no-docstrings',
])
except getopt.error, msg:
except getopt.error as msg:
usage(1, msg)
# for holding option values
@ -570,7 +574,7 @@ def main():
elif opt in ('-v', '--verbose'):
options.verbose = 1
elif opt in ('-V', '--version'):
print _('pygettext.py (xgettext for Python) %s') % __version__
print(_('pygettext.py (xgettext for Python) %s') % __version__)
sys.exit(0)
elif opt in ('-w', '--width'):
try:
@ -603,8 +607,8 @@ def main():
options.toexclude = fp.readlines()
fp.close()
except IOError:
print >> sys.stderr, _(
"Can't read --exclude-file: %s") % options.excludefilename
print(_(
"Can't read --exclude-file: %s") % options.excludefilename, file=sys.stderr)
sys.exit(1)
else:
options.toexclude = []
@ -623,21 +627,21 @@ def main():
for filename in args:
if filename == '-':
if options.verbose:
print _('Reading standard input')
print(_('Reading standard input'))
fp = sys.stdin
closep = 0
else:
if options.verbose:
print _('Working on %s') % filename
print(_('Working on %s') % filename)
fp = open(filename)
closep = 1
try:
eater.set_filename(filename)
try:
tokenize.tokenize(fp.readline, eater)
except tokenize.TokenError, e:
print >> sys.stderr, '%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1])
except tokenize.TokenError as e:
print('%s: %s, line %d, column %d' % (
e[0], filename, e[1][0], e[1][1]), file=sys.stderr)
finally:
if closep:
fp.close()

View File

@ -8,6 +8,9 @@ This can be called as:
This file is part of Gaphor.
"""
from __future__ import absolute_import
from __future__ import print_function
import six
__all__ = ['Compare']
try:
@ -37,7 +40,7 @@ class Compare(object):
def out(self, msg):
"""Print a message generated by report().
"""
print msg
print(msg)
def report(self, factory, element, name=None, value=None, isref=False):
"""Report an element that has differences.
@ -84,7 +87,7 @@ class Compare(object):
factory = gaphor.UML.ElementFactory()
try:
gaphor.storage.load_elements(elements, factory)
except Exception, e:
except Exception as e:
self.out('! File %s could not be loaded completely.' % filename)
self.out('! Trying to diff on parsed elements only.')
self.out(e)
@ -95,7 +98,7 @@ class Compare(object):
elements that exist in both files (they have the same id).
"""
vals = []
for key1, val1 in self.elements1.iteritems():
for key1, val1 in six.iteritems(self.elements1):
val2 = self.elements2.get(key1)
if val2:
yield (val1, val2)
@ -103,8 +106,8 @@ class Compare(object):
def check_missing_elements(self):
"""Report elements that exist in one factory, but not in the other.
"""
keys1 = self.elements1.keys()
keys2 = self.elements2.keys()
keys1 = list(self.elements1.keys())
keys2 = list(self.elements2.keys())
for key in keys1:
if key not in keys2:
self.report(self.factory1, self.elements1[key])
@ -117,8 +120,8 @@ class Compare(object):
"""Report references to other elements that are present in one
element and not in the other one.
"""
keys1 = element1.references.keys()
keys2 = element2.references.keys()
keys1 = list(element1.references.keys())
keys2 = list(element2.references.keys())
for key in keys1:
if key not in keys2:
self.report(self.factory1, element1, key)
@ -128,8 +131,8 @@ class Compare(object):
self.report(self.factory2, element2, key)
def check_differences_references(self, element1, element2):
keys1 = element1.references.keys()
keys2 = element2.references.keys()
keys1 = list(element1.references.keys())
keys2 = list(element2.references.keys())
for key in keys1:
if key in keys2:
val1 = element1.references.get(key)
@ -148,8 +151,8 @@ class Compare(object):
self.report(self.factory2, element2, key, val2, True)
def check_missing_values(self, element1, element2):
keys1 = element1.values.keys()
keys2 = element2.values.keys()
keys1 = list(element1.values.keys())
keys2 = list(element2.values.keys())
for key in keys1:
if key not in keys2:
self.report(self.factory1, element1, key)
@ -159,8 +162,8 @@ class Compare(object):
self.report(self.factory2, element2, key)
def check_differences_values(self, element1, element2):
keys1 = element1.values.keys()
keys2 = element2.values.keys()
keys1 = list(element1.values.keys())
keys2 = list(element2.values.keys())
for key in keys1:
if key in keys2:
val1 = element1.values.get(key)
@ -194,17 +197,17 @@ if __name__ == '__main__':
if arg == '-v':
show_id = True
elif arg in ('-h', '--help'):
print usage
print(usage)
sys.exit(0)
else:
print '%s: invalid option "%s".' % (sys.argv[0], arg)
print usage
print('%s: invalid option "%s".' % (sys.argv[0], arg))
print(usage)
sys.exit(1)
else:
files.append(arg)
if len(files) != 2:
print usage
print(usage)
sys.exit(1)
c = Compare(files[0], files[1])

View File

@ -1,3 +1,4 @@
from __future__ import absolute_import
import re
pattern = r'([A-Z])'