diff options
Diffstat (limited to 'Doc/howto/doanddont.rst')
-rw-r--r-- | Doc/howto/doanddont.rst | 15 |
1 files changed, 8 insertions, 7 deletions
diff --git a/Doc/howto/doanddont.rst b/Doc/howto/doanddont.rst index a322c53..07652bc 100644 --- a/Doc/howto/doanddont.rst +++ b/Doc/howto/doanddont.rst @@ -59,7 +59,7 @@ its least useful properties. Remember, you can never know for sure what names a module exports, so either take what you need --- ``from module import name1, name2``, or keep them in the -module and access on a per-need basis --- ``import module;print module.name``. +module and access on a per-need basis --- ``import module; print(module.name)``. When It Is Just Fine @@ -181,7 +181,7 @@ The following is a very popular anti-idiom :: def get_status(file): if not os.path.exists(file): - print "file not found" + print("file not found") sys.exit(1) return open(file).readline() @@ -199,7 +199,7 @@ Here is a better way to do it. :: try: return open(file).readline() except (IOError, OSError): - print "file not found" + print("file not found") sys.exit(1) In this version, \*either\* the file gets opened and the line is read (so it @@ -264,12 +264,13 @@ More useful functions in :mod:`os.path`: :func:`basename`, :func:`dirname` and There are also many useful builtin functions people seem not to be aware of for some reason: :func:`min` and :func:`max` can find the minimum/maximum of any sequence with comparable semantics, for example, yet many people write their own -:func:`max`/:func:`min`. Another highly useful function is :func:`reduce`. A -classical use of :func:`reduce` is something like :: +:func:`max`/:func:`min`. Another highly useful function is +:func:`functools.reduce`. A classical use of :func:`reduce` is something like +:: - import sys, operator + import sys, operator, functools nums = map(float, sys.argv[1:]) - print reduce(operator.add, nums)/len(nums) + print(functools.reduce(operator.add, nums) / len(nums)) This cute little script prints the average of all numbers given on the command line. The :func:`reduce` adds up all the numbers, and the rest is just some |