Skip to contentSkip to conversation

Use Python's "print" as a function, not as a keyword

PATCH In review Sebastian Morr 5 participants 5 messages Jun 15, 2016

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Use Python's "print" as a function, not as a keyword

This has changed from Version 2.6 to Version 3.0. Replace all occurrences of

    print ...

with

    print(...)

and all occurrences of

    print >> output, ...

with

    output.write(... + "\n")

---

I noticed that "make" on master spawned an "invalid syntax" error (it was caused by the "print ..." in git_remote_helpers/Makefile) and looked into how to fix that. I have Python 3.2.2 installed.

I'm afraid this way it breaks for Python 2.6. It seems to be possible to do

from __future__ import print_function

which we could install in all Python scripts.

But, as nobody seems to have cared before: Is Git designed to be compatible only with versions prior 3.0?

 contrib/ciabot/ciabot.py           |    6 +-
 contrib/fast-import/git-p4         |  140 ++++++++++++++++++------------------
 contrib/fast-import/import-zips.py |    2 +-
 contrib/gitview/gitview            |    2 +-
 contrib/hg-to-git/hg-to-git.py     |   46 ++++++------
 contrib/p4import/git-p4import.py   |    6 +-
 git-remote-testgit.py              |   26 ++++----
 git_remote_helpers/Makefile        |    2 +-
 git_remote_helpers/git/exporter.py |    6 +-
 git_remote_helpers/git/git.py      |    2 +-
 git_remote_helpers/util.py         |   12 ++--
 11 files changed, 125 insertions(+), 125 deletions(-)
contrib/ciabot/ciabot.py +3 -3
index 9775dff..10c5d22 100755
@@ -173,7 +173,7 @@ if __name__ == "__main__":
     try:
         (options, arguments) = getopt.getopt(sys.argv[1:], "np:V")
     except getopt.GetoptError, msg:
-        print "ciabot.py: " + str(msg)
+        print("ciabot.py: " + str(msg))
         raise SystemExit, 1
 
     mailit = True
@@ -183,7 +183,7 @@ if __name__ == "__main__":
         elif switch == '-n':
             mailit = False
         elif switch == '-V':
-            print "ciabot.py: version 3.2"
+            print("ciabot.py: version 3.2")
             sys.exit(0)
 
     # Cough and die if user has not specified a project
@@ -214,7 +214,7 @@ if __name__ == "__main__":
         if mailit:
             server.sendmail(fromaddr, [toaddr], message)
         else:
-            print message
+            print(message)
 
     if mailit:
         server.quit()
contrib/fast-import/git-p4 +70 -70

443 lines not on this page · raw message

contrib/fast-import/import-zips.py +1 -1
index 82f5ed3..596963b 100755
@@ -14,7 +14,7 @@ from time import mktime
 from zipfile import ZipFile
 
 if len(argv) < 2:
-	print 'Usage:', argv[0], '<zipfile>...'
+	print('Usage:', argv[0], '<zipfile>...')
 	exit(1)
 
 branch_ref = 'refs/heads/import-zips'
contrib/gitview/gitview +1 -1
index 4c99dfb..c3e74f3 100755
@@ -37,7 +37,7 @@ except ImportError:
         import gtksourceview
         have_gtksourceview = True
     except ImportError:
-        print "Running without gtksourceview2 or gtksourceview module"
+        print("Running without gtksourceview2 or gtksourceview module")
 
 re_ident = re.compile('(author|committer) (?P<ident>.*) (?P<epoch>\d+) (?P<tz>[+-]\d{4})')
 
contrib/hg-to-git/hg-to-git.py +23 -23

119 lines not on this page · raw message

contrib/p4import/git-p4import.py +3 -3
index b6e534b..144fafc 100644
@@ -26,11 +26,11 @@ if s != default_int_handler:
 def die(msg, *args):
     for a in args:
         msg = "%s %s" % (msg, a)
-    print "git-p4import fatal error:", msg
+    print("git-p4import fatal error:", msg)
     sys.exit(1)
 
 def usage():
-    print "USAGE: git-p4import [-q|-v]  [--authors=<file>]  [-t <timezone>]  [//p4repo/path <branch>]"
+    print("USAGE: git-p4import [-q|-v]  [--authors=<file>]  [-t <timezone>]  [//p4repo/path <branch>]")
     sys.exit(1)
 
 verbosity = 1
@@ -48,7 +48,7 @@ def report(level, msg, *args):
     fd.writelines(msg)
     fd.close()
     if level <= verbosity:
-        print msg
+        print(msg)
 
 class p4_command:
     def __init__(self, _repopath):
git-remote-testgit.py +13 -13
index 3dc4851..9803214 100644
@@ -81,9 +81,9 @@ def do_capabilities(repo, args):
     """Prints the supported capabilities.
     """
 
-    print "import"
-    print "export"
-    print "refspec refs/heads/*:%s*" % repo.prefix
+    print("import")
+    print("export")
+    print("refspec refs/heads/*:%s*" % repo.prefix)
 
     dirname = repo.get_base_path(repo.gitdir)
 
@@ -92,11 +92,11 @@ def do_capabilities(repo, args):
 
     path = os.path.join(dirname, 'testgit.marks')
 
-    print "*export-marks %s" % path
+    print("*export-marks %s" % path)
     if os.path.exists(path):
-        print "*import-marks %s" % path
+        print("*import-marks %s" % path)
 
-    print # end capabilities
+    print() # end capabilities
 
 
 def do_list(repo, args):
@@ -109,16 +109,16 @@ def do_list(repo, args):
 
     for ref in repo.revs:
         debug("? refs/heads/%s", ref)
-        print "? refs/heads/%s" % ref
+        print("? refs/heads/%s" % ref)
 
     if repo.head:
         debug("@refs/heads/%s HEAD" % repo.head)
-        print "@refs/heads/%s HEAD" % repo.head
+        print("@refs/heads/%s HEAD" % repo.head)
     else:
         debug("@refs/heads/master HEAD")
-        print "@refs/heads/master HEAD"
+        print("@refs/heads/master HEAD")
 
-    print # end list
+    print() # end list
 
 
 def update_local_repo(repo):
@@ -161,7 +161,7 @@ def do_import(repo, args):
     repo = update_local_repo(repo)
     repo.exporter.export_repo(repo.gitdir, refs)
 
-    print "done"
+    print("done")
 
 
 def do_export(repo, args):
@@ -178,8 +178,8 @@ def do_export(repo, args):
         repo.non_local.push(repo.gitdir)
 
     for ref in changed:
-        print "ok %s" % ref
-    print
+        print("ok %s" % ref)
+    print()
 
 
 COMMANDS = {
git_remote_helpers/Makefile +1 -1
index 74b05dc..f65f064 100644
@@ -23,7 +23,7 @@ endif
 
 PYLIBDIR=$(shell $(PYTHON_PATH) -c \
 	 "import sys; \
-	 print 'lib/python%i.%i/site-packages' % sys.version_info[:2]")
+	 print('lib/python%i.%i/site-packages' % sys.version_info[:2])")
 
 all: $(pysetupfile)
 	$(QUIET)$(PYTHON_PATH) $(pysetupfile) $(QUIETSETUP) build
git_remote_helpers/git/exporter.py +3 -3
index 9ee5f96..e6ad51e 100644
@@ -38,10 +38,10 @@ class GitExporter(object):
         if not os.path.exists(dirname):
             os.makedirs(dirname)
 
-        print "feature relative-marks"
+        print("feature relative-marks")
         if os.path.exists(os.path.join(dirname, 'git.marks')):
-            print "feature import-marks=%s/git.marks" % self.repo.hash
-        print "feature export-marks=%s/git.marks" % self.repo.hash
+            print("feature import-marks=%s/git.marks" % self.repo.hash)
+        print("feature export-marks=%s/git.marks" % self.repo.hash)
         sys.stdout.flush()
 
         args = ["git", "--git-dir=" + self.repo.gitpath, "fast-export", "--export-marks=" + path]
git_remote_helpers/git/git.py +1 -1
index 007a1bf..43f6c53 100644
@@ -111,7 +111,7 @@ class GitObjectFetcher(object):
         """
         if self.queue and self.in_transit is None:
             self.in_transit = self.queue.pop(0)
-            print >> self.proc.stdin, self.in_transit[0]
+            self.proc.stdin.write(self.in_transit[0] + "\n")
 
     def push (self, obj, callback):
         """Push the given object name onto the queue.
git_remote_helpers/util.py +6 -6
index fbbb01b..f6bd42e 100644
@@ -32,20 +32,20 @@ DEBUG = False
 
 def notify(msg, *args):
     """Print a message to stderr."""
-    print >> sys.stderr, msg % args
+    sys.stderr.write(msg % args + "\n")
 
 def debug (msg, *args):
     """Print a debug message to stderr when DEBUG is enabled."""
     if DEBUG:
-        print >> sys.stderr, msg % args
+        sys.stderr.write(msg % args + "\n")
 
 def error (msg, *args):
     """Print an error message to stderr."""
-    print >> sys.stderr, "ERROR:", msg % args
+    sys.stderr.write("ERROR: " + msg % args + "\n")
 
 def warn(msg, *args):
     """Print a warning message to stderr."""
-    print >> sys.stderr, "warning:", msg % args
+    sys.stderr.write("warning: " + msg % args + "\n")
 
 def die (msg, *args):
     """Print as error message to stderr and exit the program."""
@@ -87,10 +87,10 @@ class ProgressIndicator(object):
         if msg is None:
             msg = self.States[self.n % len(self.States)]
         msg = self.prefix + msg
-        print >> self.f, "\r%-*s" % (self.prev_len, msg),
+        self.f.write("\r%-*s" % (self.prev_len, msg) + "\n")
         self.prev_len = len(msg.expandtabs())
         if lf:
-            print >> self.f
+            self.f.write("\n")
             self.prev_len = 0
         self.n += 1
 
Signature · 1 line
1.7.8.382.g9f1d9.dirty
#1 lore raw
Quoted 2 lines · Sebastian Morr

But, as nobody seems to have cared before: Is Git designed to be compatible only with versions prior 3.0?

I'm running Debian unstable and it has Python 2.7. Most people are still using Python 2.x as their default system Python since 3.x breaks backwards compatibility for common constructs like print.

Does this only break Python 2.6, or all 2.x versions of Python?

What's our currently supported Python version for the Python code in Git? It's 5.8.0 for Perl, do we have any particular aim for a supported Python version?

#2 lore raw
Quoted 9 lines · Ævar Arnfjörð Bjarmason

I'm running Debian unstable and it has Python 2.7. Most people are still using Python 2.x as their default system Python since 3.x breaks backwards compatibility for common constructs like print.

Does this only break Python 2.6, or all 2.x versions of Python?

What's our currently supported Python version for the Python code in Git? It's 5.8.0 for Perl, do we have any particular aim for a supported Python version?

Python 2.4.

Signature · 3 lines
Cheers,

Sverre Rabbelier
#3 lore raw
In reply to Ævar Arnfjörð Bjarmason

[email protected] wrote on Wed, 21 Dec 2011 03:48 +0100:

Quoted 9 lines · Sebastian Morr
Quoted 3 lines

But, as nobody seems to have cared before: Is Git designed to be compatible only with versions prior 3.0?

I'm running Debian unstable and it has Python 2.7. Most people are still using Python 2.x as their default system Python since 3.x breaks backwards compatibility for common constructs like print.

Quoted 5 lines

Does this only break Python 2.6, or all 2.x versions of Python?

What's our currently supported Python version for the Python code in Git? It's 5.8.0 for Perl, do we have any particular aim for a supported Python version?

I test contrib/fast-import/git-p4 on python 2.5 and 2.7. I'm hesitant to convert print() now, without committing to testing on post-3.0 too. The work to support 3.x doesn't buy us much.

		-- Pete
#4 lore raw
In reply to Sebastian Morr
Quoted 8 lines · Sebastian Morr

This has changed from Version 2.6 to Version 3.0. Replace all occurrences of

   print ...

with

   print(...)

Quoted 7 lines

and all occurrences of

   print >> output, ...

with

   output.write(... + "\n")

While it's good to look forward, you shouldn't forget about testing on python 2.6. Lots of people still stick to that and maybe even to earlier versions.

Quoted 5 lines

 if len(argv) < 2:
-       print 'Usage:', argv[0], '<zipfile>...'
+       print('Usage:', argv[0], '<zipfile>...')
       exit(1)

Here I would use the % notation:
print('Usage: %s <zipfile>...' % argv[0])

Python 2.x would print a tuple:

Quoted 2 lines
Quoted 2 lines
Quoted 2 lines

argv = ('import-zips.py',)
print("Usage:", argv[0], '<zipfile>...')

('Usage:', 'import-zips.py', '<zipfile>...')

You could probably get away with

print('Usage: ' + argv[0] + ' <zipfile>...')

But that could probably become a readability issue. I would even wonder if it's considered pythonic.

It happens a few times more:

Quoted 84 lines

 if verbose:
-    print 'tip is', tip
+    print('tip is', tip)

contrib/hg-to-git/hg-to-git.py +6 -6
@@ -176,27 +176,27 @@ for cset in range(int(tip) + 1):
     os.write(fdcomment, csetcomment)
     os.close(fdcomment)
 
-    print '-----------------------------------------'
-    print 'cset:', cset
-    print 'branch:', hgbranch[str(cset)]
-    print 'user:', user
-    print 'date:', date
-    print 'comment:', csetcomment
+    print('-----------------------------------------')
+    print('cset:', cset)
+    print('branch:', hgbranch[str(cset)])
+    print('user:', user)
+    print('date:', date)
+    print('comment:', csetcomment)

    if parent:
-       print 'parent:', parent
+       print('parent:', parent)
    if mparent:
-        print 'mparent:', mparent
+        print('mparent:', mparent)
    if tag:
-        print 'tag:', tag
-    print '-----------------------------------------'
+        print('tag:', tag)
+    print('-----------------------------------------')

    # checkout the parent if necessary
    if cset != 0:
        if hgbranch[str(cset)] == "branch-" + str(cset):
-            print 'creating new branch', hgbranch[str(cset)]
+            print('creating new branch', hgbranch[str(cset)])
            os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent]))
        else:
-            print 'checking out branch', hgbranch[str(cset)]
+            print('checking out branch', hgbranch[str(cset)])
            os.system('git checkout %s' % hgbranch[str(cset)])
    # merge
(quoted diff) +0 -0
@@ -205,7 +205,7 @@ for cset in range(int(tip) + 1):

            otherbranch = hgbranch[mparent]
        else:
            otherbranch = hgbranch[parent]
-        print 'merging', otherbranch, 'into', hgbranch[str(cset)]
+        print('merging', otherbranch, 'into', hgbranch[str(cset)])
        os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch))

    # remove everything except .git and .hg directories
contrib/hg-to-git/hg-to-git.py +0 -0
@@ -229,12 +229,12 @@ for cset in range(int(tip) + 1):
 
     # delete branch if not used anymore...

    if mparent and len(hgchildren[str(cset)]):
-        print "Deleting unused branch:", otherbranch
+        print("Deleting unused branch:", otherbranch) os.system('git branch -d %s' % otherbranch)

    # retrieve and record the version
    vvv = os.popen('git show --quiet --pretty=format:%H').read()
-    print 'record', cset, '->', vvv
+    print('record', cset, '->', vvv)
    hgvers[str(cset)] = vvv

 if hgnewcsets >= opt_nrepack and opt_nrepack != -1:

contrib/hg-to-git/hg-to-git.py +0 -0
@@ -243,7 +243,7 @@ if hgnewcsets >= opt_nrepack and opt_nrepack != -1:
  # write the state for incrementals

 if state:
    if verbose:
-        print 'Writing state'
+        print('Writing state')
    f = open(state, 'w')
    pickle.dump(hgvers, f)

contrib/p4import/git-p4import.py +0 -0
index b6e534b..144fafc 100644
@@ -26,11 +26,11 @@ if s != default_int_handler:
Quoted 7 lines

 def die(msg, *args):
    for a in args:
        msg = "%s %s" % (msg, a)
-    print "git-p4import fatal error:", msg
+    print("git-p4import fatal error:", msg)
    sys.exit(1)

I think that's it for the print(...,...) stuff. I might have misssed one or two though.

Quoted 27 lines
git-remote-testgit.py +0 -0
index 3dc4851..9803214 100644
@@ -81,9 +81,9 @@ def do_capabilities(repo, args):

    """Prints the supported capabilities.
    """

-    print "import"
-    print "export"
-    print "refspec refs/heads/*:%s*" % repo.prefix
+    print("import")
+    print("export")
+    print("refspec refs/heads/*:%s*" % repo.prefix)

    dirname = repo.get_base_path(repo.gitdir)

git-remote-testgit.py +1 -1
@@ -92,11 +92,11 @@ def do_capabilities(repo, args):
 
     path = os.path.join(dirname, 'testgit.marks')
 
-    print "*export-marks %s" % path
+    print("*export-marks %s" % path)

    if os.path.exists(path):
-        print "*import-marks %s" % path
+        print("*import-marks %s" % path)

Quoted 2 lines

-    print # end capabilities
+    print() # end capabilities

print("") here. 2.x:

Quoted 1 line
Quoted 1 line
Quoted 1 line

print()

()

Quoted 19 lines

 def do_list(repo, args):

git-remote-testgit.py +0 -0
@@ -109,16 +109,16 @@ def do_list(repo, args):
 

    for ref in repo.revs:
        debug("? refs/heads/%s", ref)
-        print "? refs/heads/%s" % ref
+        print("? refs/heads/%s" % ref)

    if repo.head:
        debug("@refs/heads/%s HEAD" % repo.head)
-        print "@refs/heads/%s HEAD" % repo.head
+        print("@refs/heads/%s HEAD" % repo.head)
    else:
        debug("@refs/heads/master HEAD")
-        print "@refs/heads/master HEAD"
+        print("@refs/heads/master HEAD")

Quoted 2 lines

-    print # end list
+    print() # end list

print("")

Lots more to do, I'm afraid.

Cheers,
Frans