Python-checkins
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2003 -----
- December
- November
- October
- September
- August
November 2010
- 16 participants
- 934 discussions
r86773 - in python/branches/release27-maint: .hgeol Doc/library/warnings.rst Misc/gdbinit Modules/_io/fileio.c Tools/freeze/makeconfig.py Tools/freeze/winmakemakefile.py Tools/scripts/h2py.py
by georg.brandl Nov. 26, 2010
by georg.brandl Nov. 26, 2010
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 09:10:41 2010
New Revision: 86773
Log:
Merged revisions 85768-85771,85773,85777,85823,85825 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85768 | georg.brandl | 2010-10-21 14:59:14 +0200 (Do, 21 Okt 2010) | 1 line
#9919: fix off-by-one error in lineno command in Misc/gdbinit; also add newline to its output.
........
r85769 | georg.brandl | 2010-10-21 15:01:23 +0200 (Do, 21 Okt 2010) | 1 line
Fix missing import.
........
r85770 | georg.brandl | 2010-10-21 15:29:10 +0200 (Do, 21 Okt 2010) | 1 line
#3077: fix h2py substitution of character literals.
........
r85771 | georg.brandl | 2010-10-21 15:34:51 +0200 (Do, 21 Okt 2010) | 1 line
#1203650: allow larger list of files in windows makefile for freeze.
........
r85773 | georg.brandl | 2010-10-21 15:45:52 +0200 (Do, 21 Okt 2010) | 1 line
#4829: better error message for invalid file mode
........
r85777 | georg.brandl | 2010-10-21 17:44:51 +0200 (Do, 21 Okt 2010) | 1 line
Add .hgeol file for the Mercurial EOL extension.
........
r85823 | georg.brandl | 2010-10-24 16:32:45 +0200 (So, 24 Okt 2010) | 1 line
Fix style.
........
r85825 | georg.brandl | 2010-10-24 17:16:02 +0200 (So, 24 Okt 2010) | 1 line
Add documentation about the default warnings filters.
........
Added:
python/branches/release27-maint/.hgeol
- copied unchanged from r85777, /python/branches/py3k/.hgeol
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Doc/library/warnings.rst
python/branches/release27-maint/Misc/gdbinit
python/branches/release27-maint/Modules/_io/fileio.c
python/branches/release27-maint/Tools/freeze/makeconfig.py
python/branches/release27-maint/Tools/freeze/winmakemakefile.py
python/branches/release27-maint/Tools/scripts/h2py.py
Modified: python/branches/release27-maint/Doc/library/warnings.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/warnings.rst (original)
+++ python/branches/release27-maint/Doc/library/warnings.rst Fri Nov 26 09:10:41 2010
@@ -152,6 +152,25 @@
are ignored, after printing a message to ``sys.stderr``).
+Default Warning Filters
+~~~~~~~~~~~~~~~~~~~~~~~
+
+By default, Python installs several warning filters, which can be overridden by
+the command-line options passed to :option:`-W` and calls to
+:func:`filterwarnings`.
+
+* :exc:`DeprecationWarning` and :exc:`PendingDeprecationWarning`, and
+ :exc:`ImportWarning` are ignored.
+
+* :exc:`BytesWarning` is ignored unless the :option:`-b` option is given once or
+ twice; in this case this warning is either printed (``-b``) or turned into an
+ exception (``-bb`).
+
+.. versionchanged:: 3.2
+ :exc:`DeprecationWarning` is now ignored by default in addition to
+ :exc:`PendingDeprecationWarning`.
+
+
.. _warning-suppress:
Temporarily Suppressing Warnings
Modified: python/branches/release27-maint/Misc/gdbinit
==============================================================================
--- python/branches/release27-maint/Misc/gdbinit (original)
+++ python/branches/release27-maint/Misc/gdbinit Fri Nov 26 09:10:41 2010
@@ -61,11 +61,12 @@
set $__p = $__p + 1
if ($__ad > $__lasti)
set $__continue = 0
+ else
+ set $__li = $__li + *$__p
+ set $__p = $__p + 1
end
- set $__li = $__li + *$__p
- set $__p = $__p + 1
end
- printf "%d", $__li
+ printf "%d\n", $__li
end
# print the current frame - verbose
Modified: python/branches/release27-maint/Modules/_io/fileio.c
==============================================================================
--- python/branches/release27-maint/Modules/_io/fileio.c (original)
+++ python/branches/release27-maint/Modules/_io/fileio.c Fri Nov 26 09:10:41 2010
@@ -268,7 +268,8 @@
if (rwa) {
bad_mode:
PyErr_SetString(PyExc_ValueError,
- "Must have exactly one of read/write/append mode");
+ "Must have exactly one of read/write/append "
+ "mode and at most one plus");
goto error;
}
rwa = 1;
Modified: python/branches/release27-maint/Tools/freeze/makeconfig.py
==============================================================================
--- python/branches/release27-maint/Tools/freeze/makeconfig.py (original)
+++ python/branches/release27-maint/Tools/freeze/makeconfig.py Fri Nov 26 09:10:41 2010
@@ -1,5 +1,5 @@
import re
-
+import sys
# Write the config.c file
@@ -38,7 +38,6 @@
# Test program.
def test():
- import sys
if not sys.argv[3:]:
print 'usage: python makeconfig.py config.c.in outputfile',
print 'modulename ...'
Modified: python/branches/release27-maint/Tools/freeze/winmakemakefile.py
==============================================================================
--- python/branches/release27-maint/Tools/freeze/winmakemakefile.py (original)
+++ python/branches/release27-maint/Tools/freeze/winmakemakefile.py Fri Nov 26 09:10:41 2010
@@ -134,12 +134,13 @@
print ; print
print "$(target)$(debug_suffix)%s: $(temp_dir) $(OBJS)" % (target_ext)
- print "\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags),
- print "\t$(OBJS) \\"
- print "\t$(LIBS) \\"
- print "\t$(ADDN_LINK_FILES) \\"
- print "\t$(pythonlib) $(lcustom) $(l_debug)\\"
+ print "\tlink -out:$(target)$(debug_suffix)%s %s" % (target_ext, target_link_flags), "@<<"
+ print "\t$(OBJS)"
+ print "\t$(LIBS)"
+ print "\t$(ADDN_LINK_FILES)"
+ print "\t$(pythonlib) $(lcustom) $(l_debug)"
print "\t$(resources)"
+ print "<<"
print
print "clean:"
print "\t-rm -f *.obj"
Modified: python/branches/release27-maint/Tools/scripts/h2py.py
==============================================================================
--- python/branches/release27-maint/Tools/scripts/h2py.py (original)
+++ python/branches/release27-maint/Tools/scripts/h2py.py Fri Nov 26 09:10:41 2010
@@ -95,7 +95,7 @@
for p in ignores:
body = p.sub(' ', body)
# replace char literals by ord(...)
- body = p_char.sub('ord(\\0)', body)
+ body = p_char.sub("ord('\\1')", body)
# Compute negative hexadecimal constants
start = 0
UMAX = 2*(sys.maxint+1)
1
0
Author: georg.brandl
Date: Fri Nov 26 09:06:52 2010
New Revision: 86772
Log:
Blocked revisions 85577,85604,85613,85633,85680-85683,85692,85787-85789 via svnmerge
........
r85577 | georg.brandl | 2010-10-16 22:33:11 +0200 (Sa, 16 Okt 2010) | 1 line
Get rid of a "unused static function" warning.
........
r85604 | georg.brandl | 2010-10-17 08:21:59 +0200 (So, 17 Okt 2010) | 1 line
Note that maxtasksperchild is new in 3.2.
........
r85613 | georg.brandl | 2010-10-17 11:43:35 +0200 (So, 17 Okt 2010) | 1 line
Fix hmac docs: it takes and returns bytes, except for hexdigest().
........
r85633 | georg.brandl | 2010-10-17 12:59:41 +0200 (So, 17 Okt 2010) | 1 line
#9204: remove mentions of removed types in the types module.
........
r85680 | georg.brandl | 2010-10-18 09:27:55 +0200 (Mo, 18 Okt 2010) | 1 line
Fix compiler warning about unused static function.
........
r85681 | georg.brandl | 2010-10-18 09:30:06 +0200 (Mo, 18 Okt 2010) | 1 line
Fix type of hash function.
........
r85682 | georg.brandl | 2010-10-18 09:32:48 +0200 (Mo, 18 Okt 2010) | 1 line
Remove unneeded casts to hashfunc.
........
r85683 | georg.brandl | 2010-10-18 09:35:09 +0200 (Mo, 18 Okt 2010) | 1 line
Remove more unneeded casts to hashfunc.
........
r85692 | georg.brandl | 2010-10-18 14:24:53 +0200 (Mo, 18 Okt 2010) | 1 line
Fix hash function type.
........
r85787 | georg.brandl | 2010-10-22 08:28:01 +0200 (Fr, 22 Okt 2010) | 1 line
#10166: rewrite self-recursion to iteration in pstats.Stats.add(). Also add a unittest and a stats test file.
........
r85788 | georg.brandl | 2010-10-22 08:29:21 +0200 (Fr, 22 Okt 2010) | 1 line
Make top_level attribute a set instead of a dict with None values.
........
r85789 | georg.brandl | 2010-10-22 08:35:59 +0200 (Fr, 22 Okt 2010) | 1 line
Refactor interesting use of try-finally.
........
Modified:
python/branches/release27-maint/ (props changed)
1
0
r86771 - in python/branches/release27-maint: Lib/test/test_rlcompleter.py Tools/scripts/patchcheck.py Tools/scripts/reindent-rst.py Tools/scripts/untabify.py
by georg.brandl Nov. 26, 2010
by georg.brandl Nov. 26, 2010
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 09:04:57 2010
New Revision: 86771
Log:
Merged revisions 85766-85767 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85766 | georg.brandl | 2010-10-21 09:40:03 +0200 (Do, 21 Okt 2010) | 1 line
#10159: sort completion matches before comparing to dir() result.
........
r85767 | georg.brandl | 2010-10-21 14:49:28 +0200 (Do, 21 Okt 2010) | 1 line
#9095, #8912, #8999: add support in patchcheck for Mercurial checkouts, C file reindenting, and docs whitespace fixing.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Lib/test/test_rlcompleter.py
python/branches/release27-maint/Tools/scripts/patchcheck.py
python/branches/release27-maint/Tools/scripts/reindent-rst.py
python/branches/release27-maint/Tools/scripts/untabify.py
Modified: python/branches/release27-maint/Lib/test/test_rlcompleter.py
==============================================================================
--- python/branches/release27-maint/Lib/test/test_rlcompleter.py (original)
+++ python/branches/release27-maint/Lib/test/test_rlcompleter.py Fri Nov 26 09:04:57 2010
@@ -31,9 +31,9 @@
def test_global_matches(self):
# test with builtins namespace
- self.assertEqual(self.stdcompleter.global_matches('di'),
+ self.assertEqual(sorted(self.stdcompleter.global_matches('di')),
[x+'(' for x in dir(builtins) if x.startswith('di')])
- self.assertEqual(self.stdcompleter.global_matches('st'),
+ self.assertEqual(sorted(self.stdcompleter.global_matches('st')),
[x+'(' for x in dir(builtins) if x.startswith('st')])
self.assertEqual(self.stdcompleter.global_matches('akaksajadhak'), [])
Modified: python/branches/release27-maint/Tools/scripts/patchcheck.py
==============================================================================
--- python/branches/release27-maint/Tools/scripts/patchcheck.py (original)
+++ python/branches/release27-maint/Tools/scripts/patchcheck.py Fri Nov 26 09:04:57 2010
@@ -1,8 +1,16 @@
+import re
+import sys
+import shutil
import os.path
import subprocess
-import sys
import reindent
+import untabify
+
+
+def n_files_str(count):
+ """Return 'N file(s)' with the proper plurality on 'file'."""
+ return "{} file{}".format(count, "s" if count != 1 else "")
def status(message, modal=False, info=None):
@@ -17,53 +25,105 @@
elif info:
print info(result)
else:
- if result:
- print "yes"
- else:
- print "NO"
+ print "yes" if result else "NO"
return result
return call_fxn
return decorated_fxn
+
@status("Getting the list of files that have been added/changed",
- info=lambda x: "%s files" % len(x))
+ info=lambda x: n_files_str(len(x)))
def changed_files():
- """Run ``svn status`` and return a set of files that have been
- changed/added."""
- cmd = 'svn status --quiet --non-interactive --ignore-externals'
- svn_st = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
- svn_st.wait()
- output = [line.strip() for line in svn_st.stdout.readlines()]
- files = set()
- for line in output:
- if not line[0] in ('A', 'M'):
- continue
- line_parts = line.split()
- path = line_parts[-1]
- if os.path.isfile(path):
- files.add(path)
- return files
+ """Get the list of changed or added files from the VCS."""
+ if os.path.isdir('.hg'):
+ vcs = 'hg'
+ cmd = 'hg status --added --modified --no-status'
+ elif os.path.isdir('.svn'):
+ vcs = 'svn'
+ cmd = 'svn status --quiet --non-interactive --ignore-externals'
+ else:
+ sys.exit('need a checkout to get modified files')
+
+ st = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
+ try:
+ st.wait()
+ if vcs == 'hg':
+ return [x.decode().rstrip() for x in st.stdout]
+ else:
+ output = (x.decode().rstrip().rsplit(None, 1)[-1]
+ for x in st.stdout if x[0] in 'AM')
+ return set(path for path in output if os.path.isfile(path))
+ finally:
+ st.stdout.close()
+
+
+def report_modified_files(file_paths):
+ count = len(file_paths)
+ if count == 0:
+ return n_files_str(count)
+ else:
+ lines = ["{}:".format(n_files_str(count))]
+ for path in file_paths:
+ lines.append(" {}".format(path))
+ return "\n".join(lines)
+
-@status("Fixing whitespace", info=lambda x: "%s files" % x)
+@status("Fixing whitespace", info=report_modified_files)
def normalize_whitespace(file_paths):
"""Make sure that the whitespace for .py files have been normalized."""
reindent.makebackup = False # No need to create backups.
- result = map(reindent.check, (x for x in file_paths if x.endswith('.py')))
- return sum(result)
+ fixed = []
+ for path in (x for x in file_paths if x.endswith('.py')):
+ if reindent.check(path):
+ fixed.append(path)
+ return fixed
+
+
+@status("Fixing C file whitespace", info=report_modified_files)
+def normalize_c_whitespace(file_paths):
+ """Report if any C files """
+ fixed = []
+ for path in file_paths:
+ with open(path, 'r') as f:
+ if '\t' not in f.read():
+ continue
+ untabify.process(path, 8, verbose=False)
+ fixed.append(path)
+ return fixed
+
+
+ws_re = re.compile(br'\s+(\r?\n)$')
+
+@status("Fixing docs whitespace", info=report_modified_files)
+def normalize_docs_whitespace(file_paths):
+ fixed = []
+ for path in file_paths:
+ try:
+ with open(path, 'rb') as f:
+ lines = f.readlines()
+ new_lines = [ws_re.sub(br'\1', line) for line in lines]
+ if new_lines != lines:
+ shutil.copyfile(path, path + '.bak')
+ with open(path, 'wb') as f:
+ f.writelines(new_lines)
+ fixed.append(path)
+ except Exception as err:
+ print 'Cannot fix %s: %s' % (path, err)
+ return fixed
+
@status("Docs modified", modal=True)
def docs_modified(file_paths):
- """Report if any files in the Docs directory."""
- for path in file_paths:
- if path.startswith("Doc"):
- return True
- return False
+ """Report if any file in the Doc directory has been changed."""
+ return bool(file_paths)
+
@status("Misc/ACKS updated", modal=True)
def credit_given(file_paths):
"""Check if Misc/ACKS has been changed."""
return 'Misc/ACKS' in file_paths
+
@status("Misc/NEWS updated", modal=True)
def reported_news(file_paths):
"""Check if Misc/NEWS has been changed."""
@@ -72,14 +132,22 @@
def main():
file_paths = changed_files()
- # PEP 7/8 verification.
- normalize_whitespace(file_paths)
+ python_files = [fn for fn in file_paths if fn.endswith('.py')]
+ c_files = [fn for fn in file_paths if fn.endswith(('.c', '.h'))]
+ doc_files = [fn for fn in file_paths if fn.startswith('Doc')]
+ special_files = {'Misc/ACKS', 'Misc/NEWS'} & set(file_paths)
+ # PEP 8 whitespace rules enforcement.
+ normalize_whitespace(python_files)
+ # C rules enforcement.
+ normalize_c_whitespace(c_files)
+ # Doc whitespace enforcement.
+ normalize_docs_whitespace(doc_files)
# Docs updated.
- docs_modified(file_paths)
+ docs_modified(doc_files)
# Misc/ACKS changed.
- credit_given(file_paths)
+ credit_given(special_files)
# Misc/NEWS changed.
- reported_news(file_paths)
+ reported_news(special_files)
# Test suite run and passed.
print
Modified: python/branches/release27-maint/Tools/scripts/reindent-rst.py
==============================================================================
--- python/branches/release27-maint/Tools/scripts/reindent-rst.py (original)
+++ python/branches/release27-maint/Tools/scripts/reindent-rst.py Fri Nov 26 09:04:57 2010
@@ -3,27 +3,12 @@
# Make a reST file compliant to our pre-commit hook.
# Currently just remove trailing whitespace.
-from __future__ import with_statement
-import sys, re, shutil
+import sys
-ws_re = re.compile(r'\s+(\r?\n)$')
+import patchcheck
def main(argv=sys.argv):
- rv = 0
- for filename in argv[1:]:
- try:
- with open(filename, 'rb') as f:
- lines = f.readlines()
- new_lines = [ws_re.sub(r'\1', line) for line in lines]
- if new_lines != lines:
- print 'Fixing %s...' % filename
- shutil.copyfile(filename, filename + '.bak')
- with open(filename, 'wb') as f:
- f.writelines(new_lines)
- except Exception, err:
- print 'Cannot fix %s: %s' % (filename, err)
- rv = 1
- return rv
+ patchcheck.normalize_docs_whitespace(argv[1:])
if __name__ == '__main__':
sys.exit(main())
Modified: python/branches/release27-maint/Tools/scripts/untabify.py
==============================================================================
--- python/branches/release27-maint/Tools/scripts/untabify.py (original)
+++ python/branches/release27-maint/Tools/scripts/untabify.py Fri Nov 26 09:04:57 2010
@@ -23,7 +23,7 @@
for filename in args:
process(filename, tabsize)
-def process(filename, tabsize):
+def process(filename, tabsize, verbose=True):
try:
f = open(filename)
text = f.read()
@@ -43,10 +43,10 @@
os.rename(filename, backup)
except os.error:
pass
- f = open(filename, "w")
- f.write(newtext)
- f.close()
- print filename
+ with open(filename, "w") as f:
+ f.write(newtext)
+ if verbose:
+ print filename
if __name__ == '__main__':
main()
1
0
r86770 - in python/branches/release27-maint: Doc/c-api/init.rst Doc/library/locale.rst Doc/library/multiprocessing.rst Doc/library/runpy.rst Doc/library/threading.rst Lib/test/test_calendar.py
by georg.brandl Nov. 26, 2010
by georg.brandl Nov. 26, 2010
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 08:58:55 2010
New Revision: 86770
Log:
Merged revisions 85731,85735 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85731 | georg.brandl | 2010-10-19 23:07:16 +0200 (Di, 19 Okt 2010) | 1 line
Be consistent in the spelling of thread-safe(ty).
........
r85735 | georg.brandl | 2010-10-20 08:50:19 +0200 (Mi, 20 Okt 2010) | 1 line
Fix r85728: use "" to mean the system default locale, which should work on more systems.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Doc/c-api/init.rst
python/branches/release27-maint/Doc/library/locale.rst
python/branches/release27-maint/Doc/library/multiprocessing.rst
python/branches/release27-maint/Doc/library/runpy.rst
python/branches/release27-maint/Doc/library/threading.rst
python/branches/release27-maint/Lib/test/test_calendar.py
Modified: python/branches/release27-maint/Doc/c-api/init.rst
==============================================================================
--- python/branches/release27-maint/Doc/c-api/init.rst (original)
+++ python/branches/release27-maint/Doc/c-api/init.rst Fri Nov 26 08:58:55 2010
@@ -418,7 +418,7 @@
single: interpreter lock
single: lock, interpreter
-The Python interpreter is not fully thread safe. In order to support
+The Python interpreter is not fully thread-safe. In order to support
multi-threaded Python programs, there's a global lock, called the :dfn:`global
interpreter lock` or :dfn:`GIL`, that must be held by the current thread before
it can safely access Python objects. Without the lock, even the simplest
Modified: python/branches/release27-maint/Doc/library/locale.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/locale.rst (original)
+++ python/branches/release27-maint/Doc/library/locale.rst Fri Nov 26 08:58:55 2010
@@ -40,7 +40,7 @@
If *locale* is omitted or ``None``, the current setting for *category* is
returned.
- :func:`setlocale` is not thread safe on most systems. Applications typically
+ :func:`setlocale` is not thread-safe on most systems. Applications typically
start with a call of ::
import locale
Modified: python/branches/release27-maint/Doc/library/multiprocessing.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/multiprocessing.rst (original)
+++ python/branches/release27-maint/Doc/library/multiprocessing.rst Fri Nov 26 08:58:55 2010
@@ -216,7 +216,7 @@
The ``'d'`` and ``'i'`` arguments used when creating ``num`` and ``arr`` are
typecodes of the kind used by the :mod:`array` module: ``'d'`` indicates a
double precision float and ``'i'`` indicates a signed integer. These shared
- objects will be process and thread safe.
+ objects will be process and thread-safe.
For more flexibility in using shared memory one can use the
:mod:`multiprocessing.sharedctypes` module which supports the creation of
Modified: python/branches/release27-maint/Doc/library/runpy.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/runpy.rst (original)
+++ python/branches/release27-maint/Doc/library/runpy.rst Fri Nov 26 08:58:55 2010
@@ -120,7 +120,7 @@
Note that, unlike :func:`run_module`, the alterations made to :mod:`sys`
are not optional in this function as these adjustments are essential to
- allowing the execution of sys.path entries. As the thread safety
+ allowing the execution of sys.path entries. As the thread-safety
limitations still apply, use of this function in threaded code should be
either serialised with the import lock or delegated to a separate process.
Modified: python/branches/release27-maint/Doc/library/threading.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/threading.rst (original)
+++ python/branches/release27-maint/Doc/library/threading.rst Fri Nov 26 08:58:55 2010
@@ -781,9 +781,9 @@
Importing in threaded code
--------------------------
-While the import machinery is thread safe, there are two key
-restrictions on threaded imports due to inherent limitations in the way
-that thread safety is provided:
+While the import machinery is thread-safe, there are two key restrictions on
+threaded imports due to inherent limitations in the way that thread-safety is
+provided:
* Firstly, other than in the main module, an import should not have the
side effect of spawning a new thread and then waiting for that thread in
Modified: python/branches/release27-maint/Lib/test/test_calendar.py
==============================================================================
--- python/branches/release27-maint/Lib/test/test_calendar.py (original)
+++ python/branches/release27-maint/Lib/test/test_calendar.py Fri Nov 26 08:58:55 2010
@@ -252,16 +252,13 @@
def test_localecalendars(self):
# ensure that Locale{Text,HTML}Calendar resets the locale properly
# (it is still not thread-safe though)
+ old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
try:
- def_locale = locale.getdefaultlocale()
+ calendar.LocaleTextCalendar(locale='').formatmonthname(2010, 10, 10)
except locale.Error:
- # cannot determine a default locale -- skip test
+ # cannot set the system default locale -- skip rest of test
return
- old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
- calendar.LocaleTextCalendar(
- locale=def_locale).formatmonthname(2010, 10, 10)
- calendar.LocaleHTMLCalendar(
- locale=def_locale).formatmonthname(2010, 10)
+ calendar.LocaleHTMLCalendar(locale='').formatmonthname(2010, 10)
new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
self.assertEquals(old_october, new_october)
1
0
r86769 - in python/branches/release27-maint: Doc/library/calendar.rst Lib/calendar.py Lib/test/test_calendar.py Misc/NEWS
by georg.brandl Nov. 26, 2010
by georg.brandl Nov. 26, 2010
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 08:57:57 2010
New Revision: 86769
Log:
Merged revisions 85728 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85728 | georg.brandl | 2010-10-19 20:54:25 +0200 (Di, 19 Okt 2010) | 1 line
#10092: Properly reset locale in Locale*Calendar classes. The context manager was buggy because setlocale() returns the *new* locale, not the old. Also add a test for this.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Doc/library/calendar.rst
python/branches/release27-maint/Lib/calendar.py
python/branches/release27-maint/Lib/test/test_calendar.py
python/branches/release27-maint/Misc/NEWS
Modified: python/branches/release27-maint/Doc/library/calendar.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/calendar.rst (original)
+++ python/branches/release27-maint/Doc/library/calendar.rst Fri Nov 26 08:57:57 2010
@@ -182,9 +182,9 @@
.. class:: LocaleTextCalendar([firstweekday[, locale]])
This subclass of :class:`TextCalendar` can be passed a locale name in the
- constructor and will return month and weekday names in the specified
- locale. If this locale includes an encoding all strings containing month and
- weekday names will be returned as unicode.
+ constructor and will return month and weekday names in the specified locale.
+ If this locale includes an encoding all strings containing month and weekday
+ names will be returned as unicode.
.. versionadded:: 2.5
@@ -198,6 +198,13 @@
.. versionadded:: 2.5
+.. note::
+
+ The :meth:`formatweekday` and :meth:`formatmonthname` methods of these two
+ classes temporarily change the current locale to the given *locale*. Because
+ the current locale is a process-wide setting, they are not thread-safe.
+
+
For simple text calendars this module provides the following functions.
Modified: python/branches/release27-maint/Lib/calendar.py
==============================================================================
--- python/branches/release27-maint/Lib/calendar.py (original)
+++ python/branches/release27-maint/Lib/calendar.py Fri Nov 26 08:57:57 2010
@@ -486,8 +486,8 @@
self.locale = locale
def __enter__(self):
- self.oldlocale = _locale.setlocale(_locale.LC_TIME, self.locale)
- return _locale.getlocale(_locale.LC_TIME)[1]
+ self.oldlocale = _locale.getlocale(_locale.LC_TIME)
+ _locale.setlocale(_locale.LC_TIME, self.locale)
def __exit__(self, *args):
_locale.setlocale(_locale.LC_TIME, self.oldlocale)
Modified: python/branches/release27-maint/Lib/test/test_calendar.py
==============================================================================
--- python/branches/release27-maint/Lib/test/test_calendar.py (original)
+++ python/branches/release27-maint/Lib/test/test_calendar.py Fri Nov 26 08:57:57 2010
@@ -2,6 +2,7 @@
import unittest
from test import test_support
+import locale
result_2004_text = """
@@ -248,6 +249,22 @@
# verify it "acts like a sequence" in two forms of iteration
self.assertEqual(value[::-1], list(reversed(value)))
+ def test_localecalendars(self):
+ # ensure that Locale{Text,HTML}Calendar resets the locale properly
+ # (it is still not thread-safe though)
+ try:
+ def_locale = locale.getdefaultlocale()
+ except locale.Error:
+ # cannot determine a default locale -- skip test
+ return
+ old_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
+ calendar.LocaleTextCalendar(
+ locale=def_locale).formatmonthname(2010, 10, 10)
+ calendar.LocaleHTMLCalendar(
+ locale=def_locale).formatmonthname(2010, 10)
+ new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
+ self.assertEquals(old_october, new_october)
+
class MonthCalendarTestCase(unittest.TestCase):
def setUp(self):
Modified: python/branches/release27-maint/Misc/NEWS
==============================================================================
--- python/branches/release27-maint/Misc/NEWS (original)
+++ python/branches/release27-maint/Misc/NEWS Fri Nov 26 08:57:57 2010
@@ -13,6 +13,8 @@
Library
-------
+- Issue #10092: Properly reset locale in calendar.Locale*Calendar classes.
+
- Issue #10459: Update CJK character names to Unicode 5.2.
- Issue #6098: Don't claim DOM level 3 conformance in minidom.
1
0
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 08:53:50 2010
New Revision: 86768
Log:
Merged revisions 85617-85622,85624,85626-85627,85629,85631,85635-85636,85638-85639,85641-85642 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85617 | georg.brandl | 2010-10-17 12:09:06 +0200 (So, 17 Okt 2010) | 1 line
#5212: md5 weaknesses do not affect hmac, so remove the note about that.
........
r85618 | georg.brandl | 2010-10-17 12:14:38 +0200 (So, 17 Okt 2010) | 1 line
#9086: correct wrong terminology about linking with pythonXY.dll.
........
r85619 | georg.brandl | 2010-10-17 12:15:50 +0200 (So, 17 Okt 2010) | 1 line
Make file names consistent.
........
r85620 | georg.brandl | 2010-10-17 12:22:28 +0200 (So, 17 Okt 2010) | 1 line
Remove second parser module example; it referred to non-readily-available example files, and this kind of discovery is much better done with the AST nowadays anyway.
........
r85621 | georg.brandl | 2010-10-17 12:24:54 +0200 (So, 17 Okt 2010) | 1 line
#9105: move pickle warning to a bit more prominent location.
........
r85622 | georg.brandl | 2010-10-17 12:28:04 +0200 (So, 17 Okt 2010) | 1 line
#9112: document error() and exit() methods of ArgumentParser.
........
r85624 | georg.brandl | 2010-10-17 12:34:28 +0200 (So, 17 Okt 2010) | 1 line
Some markup and style fixes in argparse docs.
........
r85626 | georg.brandl | 2010-10-17 12:38:20 +0200 (So, 17 Okt 2010) | 1 line
#9117: fix syntax for class definition.
........
r85627 | georg.brandl | 2010-10-17 12:44:11 +0200 (So, 17 Okt 2010) | 1 line
#9138: reword introduction to classes in Python.
........
r85629 | georg.brandl | 2010-10-17 12:51:45 +0200 (So, 17 Okt 2010) | 1 line
#5962: clarify sys.exit() vs. threads.
........
r85631 | georg.brandl | 2010-10-17 12:53:54 +0200 (So, 17 Okt 2010) | 1 line
Fix capitalization.
........
r85635 | georg.brandl | 2010-10-17 13:03:22 +0200 (So, 17 Okt 2010) | 1 line
#5121: fix claims about default values leading to segfaults.
........
r85636 | georg.brandl | 2010-10-17 13:06:14 +0200 (So, 17 Okt 2010) | 1 line
#9237: document sys.call_tracing().
........
r85638 | georg.brandl | 2010-10-17 13:13:37 +0200 (So, 17 Okt 2010) | 1 line
Port changes to pickle docs apparently lost in py3k.
........
r85639 | georg.brandl | 2010-10-17 13:23:56 +0200 (So, 17 Okt 2010) | 1 line
Make twisted example a bit more logical.
........
r85641 | georg.brandl | 2010-10-17 13:29:07 +0200 (So, 17 Okt 2010) | 1 line
Fix documentation of dis.opmap direction.
........
r85642 | georg.brandl | 2010-10-17 13:36:28 +0200 (So, 17 Okt 2010) | 1 line
#9730: fix example.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Doc/c-api/unicode.rst
python/branches/release27-maint/Doc/c-api/veryhigh.rst
python/branches/release27-maint/Doc/faq/windows.rst
python/branches/release27-maint/Doc/library/argparse.rst
python/branches/release27-maint/Doc/library/base64.rst
python/branches/release27-maint/Doc/library/dis.rst
python/branches/release27-maint/Doc/library/hmac.rst
python/branches/release27-maint/Doc/library/os.rst
python/branches/release27-maint/Doc/library/parser.rst
python/branches/release27-maint/Doc/library/pickle.rst
python/branches/release27-maint/Doc/library/stdtypes.rst
python/branches/release27-maint/Doc/library/sys.rst
python/branches/release27-maint/Doc/tutorial/classes.rst
Modified: python/branches/release27-maint/Doc/c-api/unicode.rst
==============================================================================
--- python/branches/release27-maint/Doc/c-api/unicode.rst (original)
+++ python/branches/release27-maint/Doc/c-api/unicode.rst Fri Nov 26 08:53:50 2010
@@ -208,7 +208,7 @@
.. cfunction:: PyObject* PyUnicode_FromUnicode(const Py_UNICODE *u, Py_ssize_t size)
- Create a Unicode Object from the Py_UNICODE buffer *u* of the given size. *u*
+ Create a Unicode object from the Py_UNICODE buffer *u* of the given size. *u*
may be *NULL* which causes the contents to be undefined. It is the user's
responsibility to fill in the needed data. The buffer is copied into the new
object. If the buffer is not *NULL*, the return value might be a shared object.
@@ -222,7 +222,7 @@
.. cfunction:: PyObject* PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size)
- Create a Unicode Object from the char buffer *u*. The bytes will be interpreted
+ Create a Unicode object from the char buffer *u*. The bytes will be interpreted
as being UTF-8 encoded. *u* may also be *NULL* which
causes the contents to be undefined. It is the user's responsibility to fill in
the needed data. The buffer is copied into the new object. If the buffer is not
Modified: python/branches/release27-maint/Doc/c-api/veryhigh.rst
==============================================================================
--- python/branches/release27-maint/Doc/c-api/veryhigh.rst (original)
+++ python/branches/release27-maint/Doc/c-api/veryhigh.rst Fri Nov 26 08:53:50 2010
@@ -121,13 +121,13 @@
.. cfunction:: int PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
- Read and execute a single statement from a file associated with an interactive
- device according to the *flags* argument. If *filename* is *NULL*, ``"???"`` is
- used instead. The user will be prompted using ``sys.ps1`` and ``sys.ps2``.
- Returns ``0`` when the input was executed successfully, ``-1`` if there was an
- exception, or an error code from the :file:`errcode.h` include file distributed
- as part of Python if there was a parse error. (Note that :file:`errcode.h` is
- not included by :file:`Python.h`, so must be included specifically if needed.)
+ Read and execute a single statement from a file associated with an
+ interactive device according to the *flags* argument. The user will be
+ prompted using ``sys.ps1`` and ``sys.ps2``. Returns ``0`` when the input was
+ executed successfully, ``-1`` if there was an exception, or an error code
+ from the :file:`errcode.h` include file distributed as part of Python if
+ there was a parse error. (Note that :file:`errcode.h` is not included by
+ :file:`Python.h`, so must be included specifically if needed.)
.. cfunction:: int PyRun_InteractiveLoop(FILE *fp, const char *filename)
@@ -136,11 +136,11 @@
leaving *flags* set to *NULL*.
-.. cfunction:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
+.. cfunction:: int PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
Read and execute statements from a file associated with an interactive device
- until EOF is reached. If *filename* is *NULL*, ``"???"`` is used instead. The
- user will be prompted using ``sys.ps1`` and ``sys.ps2``. Returns ``0`` at EOF.
+ until EOF is reached. The user will be prompted using ``sys.ps1`` and
+ ``sys.ps2``. Returns ``0`` at EOF.
.. cfunction:: struct _node* PyParser_SimpleParseString(const char *str, int start)
Modified: python/branches/release27-maint/Doc/faq/windows.rst
==============================================================================
--- python/branches/release27-maint/Doc/faq/windows.rst (original)
+++ python/branches/release27-maint/Doc/faq/windows.rst Fri Nov 26 08:53:50 2010
@@ -286,20 +286,18 @@
1. Do _not_ build Python into your .exe file directly. On Windows, Python must
be a DLL to handle importing modules that are themselves DLL's. (This is the
- first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
- typically installed in ``C:\Windows\System``. NN is the Python version, a
+ first key undocumented fact.) Instead, link to :file:`python{NN}.dll`; it is
+ typically installed in ``C:\Windows\System``. *NN* is the Python version, a
number such as "23" for Python 2.3.
- You can link to Python statically or dynamically. Linking statically means
- linking against :file:`python{NN}.lib`, while dynamically linking means
- linking against :file:`python{NN}.dll`. The drawback to dynamic linking is
- that your app won't run if :file:`python{NN}.dll` does not exist on your
- system. (General note: :file:`python{NN}.lib` is the so-called "import lib"
- corresponding to :file:`python.dll`. It merely defines symbols for the
- linker.)
+ You can link to Python in two different ways. Load-time linking means
+ linking against :file:`python{NN}.lib`, while run-time linking means linking
+ against :file:`python{NN}.dll`. (General note: :file:`python{NN}.lib` is the
+ so-called "import lib" corresponding to :file:`python{NN}.dll`. It merely
+ defines symbols for the linker.)
- Linking dynamically greatly simplifies link options; everything happens at
- run time. Your code must load :file:`python{NN}.dll` using the Windows
+ Run-time linking greatly simplifies link options; everything happens at run
+ time. Your code must load :file:`python{NN}.dll` using the Windows
``LoadLibraryEx()`` routine. The code must also use access routines and data
in :file:`python{NN}.dll` (that is, Python's C API's) using pointers obtained
by the Windows ``GetProcAddress()`` routine. Macros can make using these
@@ -308,6 +306,8 @@
Borland note: convert :file:`python{NN}.lib` to OMF format using Coff2Omf.exe
first.
+ .. XXX what about static linking?
+
2. If you use SWIG, it is easy to create a Python "extension module" that will
make the app's data and methods available to Python. SWIG will handle just
about all the grungy details for you. The result is C code that you link
Modified: python/branches/release27-maint/Doc/library/argparse.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/argparse.rst (original)
+++ python/branches/release27-maint/Doc/library/argparse.rst Fri Nov 26 08:53:50 2010
@@ -1,5 +1,5 @@
-:mod:`argparse` -- Parser for command line options, arguments and sub-commands
-==============================================================================
+:mod:`argparse` --- Parser for command line options, arguments and sub-commands
+===============================================================================
.. module:: argparse
:synopsis: Command-line option and argument parsing library.
@@ -14,6 +14,7 @@
module also automatically generates help and usage messages and issues errors
when users give the program invalid arguments.
+
Example
-------
@@ -64,6 +65,7 @@
The following sections walk you through this example.
+
Creating a parser
^^^^^^^^^^^^^^^^^
@@ -97,6 +99,7 @@
either the :func:`sum` function, if ``--sum`` was specified at the command line,
or the :func:`max` function if it was not.
+
Parsing arguments
^^^^^^^^^^^^^^^^^
@@ -248,7 +251,6 @@
+h, ++help show this help message and exit
-
prefix_chars
^^^^^^^^^^^^
@@ -295,6 +297,7 @@
The ``fromfile_prefix_chars=`` argument defaults to ``None``, meaning that
arguments will never be treated as file references.
+
argument_default
^^^^^^^^^^^^^^^^
@@ -594,6 +597,7 @@
The following sections describe how each of these are used.
+
name or flags
^^^^^^^^^^^^^
@@ -623,6 +627,7 @@
usage: PROG [-h] [-f FOO] bar
PROG: error: too few arguments
+
action
^^^^^^
@@ -767,8 +772,10 @@
output files::
>>> parser = argparse.ArgumentParser()
- >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin)
- >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), default=sys.stdout)
+ >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
+ ... default=sys.stdin)
+ >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
+ ... default=sys.stdout)
>>> parser.parse_args(['input.txt', 'output.txt'])
Namespace(infile=<open file 'input.txt', mode 'r' at 0x...>, outfile=<open file 'output.txt', mode 'w' at 0x...>)
>>> parser.parse_args([])
@@ -1128,7 +1135,7 @@
The parse_args() method
-----------------------
-.. method:: ArgumentParser.parse_args([args], [namespace])
+.. method:: ArgumentParser.parse_args(args=None, namespace=None)
Convert argument strings to objects and assign them as attributes of the
namespace. Return the populated namespace.
@@ -1140,6 +1147,7 @@
By default, the arg strings are taken from :data:`sys.argv`, and a new empty
:class:`Namespace` object is created for the attributes.
+
Option value syntax
^^^^^^^^^^^^^^^^^^^
@@ -1503,7 +1511,7 @@
Argument groups
^^^^^^^^^^^^^^^
-.. method:: ArgumentParser.add_argument_group([title], [description])
+.. method:: ArgumentParser.add_argument_group(title=None, description=None)
By default, :class:`ArgumentParser` groups command-line arguments into
"positional arguments" and "optional arguments" when displaying help
@@ -1527,7 +1535,7 @@
:class:`ArgumentParser`. When an argument is added to the group, the parser
treats it just like a normal argument, but displays the argument in a
separate group for help messages. The :meth:`add_argument_group` method
- accepts ``title`` and ``description`` arguments which can be used to
+ accepts *title* and *description* arguments which can be used to
customize this display::
>>> parser = argparse.ArgumentParser(prog='PROG', add_help=False)
@@ -1555,7 +1563,7 @@
Mutual exclusion
^^^^^^^^^^^^^^^^
-.. method:: add_mutually_exclusive_group([required=False])
+.. method:: add_mutually_exclusive_group(required=False)
Create a mutually exclusive group. argparse will make sure that only one of
the arguments in the mutually exclusive group was present on the command
@@ -1573,7 +1581,7 @@
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo
- The :meth:`add_mutually_exclusive_group` method also accepts a ``required``
+ The :meth:`add_mutually_exclusive_group` method also accepts a *required*
argument, to indicate that at least one of the mutually exclusive arguments
is required::
@@ -1586,7 +1594,7 @@
PROG: error: one of the arguments --foo --bar is required
Note that currently mutually exclusive argument groups do not support the
- ``title`` and ``description`` arguments of :meth:`add_argument_group`.
+ *title* and *description* arguments of :meth:`add_argument_group`.
Parser defaults
@@ -1637,37 +1645,36 @@
and printing any usage or error messages. However, several formatting methods
are available:
-.. method:: ArgumentParser.print_usage([file]):
+.. method:: ArgumentParser.print_usage(file=None)
Print a brief description of how the :class:`ArgumentParser` should be
- invoked on the command line. If ``file`` is not present, ``sys.stderr`` is
+ invoked on the command line. If *file* is ``None``, :data:`sys.stderr` is
assumed.
-.. method:: ArgumentParser.print_help([file]):
+.. method:: ArgumentParser.print_help(file=None)
Print a help message, including the program usage and information about the
- arguments registered with the :class:`ArgumentParser`. If ``file`` is not
- present, ``sys.stderr`` is assumed.
+ arguments registered with the :class:`ArgumentParser`. If *file* is
+ ``None``, :data:`sys.stderr` is assumed.
There are also variants of these methods that simply return a string instead of
printing it:
-.. method:: ArgumentParser.format_usage():
+.. method:: ArgumentParser.format_usage()
Return a string containing a brief description of how the
:class:`ArgumentParser` should be invoked on the command line.
-.. method:: ArgumentParser.format_help():
+.. method:: ArgumentParser.format_help()
Return a string containing a help message, including the program usage and
information about the arguments registered with the :class:`ArgumentParser`.
-
Partial parsing
^^^^^^^^^^^^^^^
-.. method:: ArgumentParser.parse_known_args([args], [namespace])
+.. method:: ArgumentParser.parse_known_args(args=None, namespace=None)
Sometimes a script may only parse a few of the command line arguments, passing
the remaining arguments on to another script or program. In these cases, the
@@ -1690,12 +1697,12 @@
.. method:: ArgumentParser.convert_arg_line_to_args(arg_line)
- Arguments that are read from a file (see the ``fromfile_prefix_chars``
+ Arguments that are read from a file (see the *fromfile_prefix_chars*
keyword argument to the :class:`ArgumentParser` constructor) are read one
argument per line. :meth:`convert_arg_line_to_args` can be overriden for
fancier reading.
- This method takes a single argument ``arg_line`` which is a string read from
+ This method takes a single argument *arg_line* which is a string read from
the argument file. It returns a list of arguments parsed from this string.
The method is called once per line read from the argument file, in order.
@@ -1709,6 +1716,20 @@
yield arg
+Exiting methods
+^^^^^^^^^^^^^^^
+
+.. method:: ArgumentParser.exit(status=0, message=None)
+
+ This method terminates the program, exiting with the specified *status*
+ and, if given, it prints a *message* before that.
+
+.. method:: ArgumentParser.error(message)
+
+ This method prints a usage message including the *message* to the
+ standard output and terminates the program with a status code of 2.
+
+
.. _argparse-from-optparse:
Upgrading optparse code
Modified: python/branches/release27-maint/Doc/library/base64.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/base64.rst (original)
+++ python/branches/release27-maint/Doc/library/base64.rst Fri Nov 26 08:53:50 2010
@@ -1,4 +1,3 @@
-
:mod:`base64` --- RFC 3548: Base16, Base32, Base64 Data Encodings
=================================================================
Modified: python/branches/release27-maint/Doc/library/dis.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/dis.rst (original)
+++ python/branches/release27-maint/Doc/library/dis.rst Fri Nov 26 08:53:50 2010
@@ -99,7 +99,7 @@
.. data:: opmap
- Dictionary mapping bytecodes to operation names.
+ Dictionary mapping operation names to bytecodes.
.. data:: cmp_op
Modified: python/branches/release27-maint/Doc/library/hmac.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/hmac.rst (original)
+++ python/branches/release27-maint/Doc/library/hmac.rst Fri Nov 26 08:53:50 2010
@@ -19,10 +19,6 @@
is made. *digestmod* is the digest constructor or module for the HMAC object to
use. It defaults to the :func:`hashlib.md5` constructor.
- .. note::
-
- The md5 hash has known weaknesses but remains the default for backwards
- compatibility. Choose a better one for your application.
An HMAC object has the following methods:
Modified: python/branches/release27-maint/Doc/library/os.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/os.rst (original)
+++ python/branches/release27-maint/Doc/library/os.rst Fri Nov 26 08:53:50 2010
@@ -1679,15 +1679,15 @@
.. function:: _exit(n)
- Exit to the system with status *n*, without calling cleanup handlers, flushing
+ Exit the process with status *n*, without calling cleanup handlers, flushing
stdio buffers, etc.
Availability: Unix, Windows.
.. note::
- The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
- be used in the child process after a :func:`fork`.
+ The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
+ normally only be used in the child process after a :func:`fork`.
The following exit codes are defined and can be used with :func:`_exit`,
although they are not required. These are typically used for system programs
Modified: python/branches/release27-maint/Doc/library/parser.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/parser.rst (original)
+++ python/branches/release27-maint/Doc/library/parser.rst Fri Nov 26 08:53:50 2010
@@ -322,22 +322,8 @@
Same as ``st2tuple(st, line_info)``.
-.. _st-examples:
-
-Examples
---------
-
-.. index:: builtin: compile
-
-The parser modules allows operations to be performed on the parse tree of Python
-source code before the :term:`bytecode` is generated, and provides for inspection of the
-parse tree for information gathering purposes. Two examples are presented. The
-simple example demonstrates emulation of the :func:`compile` built-in function
-and the complex example shows the use of a parse tree for information discovery.
-
-
-Emulation of :func:`compile`
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+Example: Emulation of :func:`compile`
+-------------------------------------
While many useful operations may take place between parsing and bytecode
generation, the simplest operation is to do nothing. For this purpose, using
@@ -371,322 +357,3 @@
def load_expression(source_string):
st = parser.expr(source_string)
return st, st.compile()
-
-
-Information Discovery
-^^^^^^^^^^^^^^^^^^^^^
-
-.. index::
- single: string; documentation
- single: docstrings
-
-Some applications benefit from direct access to the parse tree. The remainder
-of this section demonstrates how the parse tree provides access to module
-documentation defined in docstrings without requiring that the code being
-examined be loaded into a running interpreter via :keyword:`import`. This can
-be very useful for performing analyses of untrusted code.
-
-Generally, the example will demonstrate how the parse tree may be traversed to
-distill interesting information. Two functions and a set of classes are
-developed which provide programmatic access to high level function and class
-definitions provided by a module. The classes extract information from the
-parse tree and provide access to the information at a useful semantic level, one
-function provides a simple low-level pattern matching capability, and the other
-function defines a high-level interface to the classes by handling file
-operations on behalf of the caller. All source files mentioned here which are
-not part of the Python installation are located in the :file:`Demo/parser/`
-directory of the distribution.
-
-The dynamic nature of Python allows the programmer a great deal of flexibility,
-but most modules need only a limited measure of this when defining classes,
-functions, and methods. In this example, the only definitions that will be
-considered are those which are defined in the top level of their context, e.g.,
-a function defined by a :keyword:`def` statement at column zero of a module, but
-not a function defined within a branch of an :keyword:`if` ... :keyword:`else`
-construct, though there are some good reasons for doing so in some situations.
-Nesting of definitions will be handled by the code developed in the example.
-
-To construct the upper-level extraction methods, we need to know what the parse
-tree structure looks like and how much of it we actually need to be concerned
-about. Python uses a moderately deep parse tree so there are a large number of
-intermediate nodes. It is important to read and understand the formal grammar
-used by Python. This is specified in the file :file:`Grammar/Grammar` in the
-distribution. Consider the simplest case of interest when searching for
-docstrings: a module consisting of a docstring and nothing else. (See file
-:file:`docstring.py`.) ::
-
- """Some documentation.
- """
-
-Using the interpreter to take a look at the parse tree, we find a bewildering
-mass of numbers and parentheses, with the documentation buried deep in nested
-tuples. ::
-
- >>> import parser
- >>> import pprint
- >>> st = parser.suite(open('docstring.py').read())
- >>> tup = st.totuple()
- >>> pprint.pprint(tup)
- (257,
- (264,
- (265,
- (266,
- (267,
- (307,
- (287,
- (288,
- (289,
- (290,
- (292,
- (293,
- (294,
- (295,
- (296,
- (297,
- (298,
- (299,
- (300, (3, '"""Some documentation.\n"""'))))))))))))))))),
- (4, ''))),
- (4, ''),
- (0, ''))
-
-The numbers at the first element of each node in the tree are the node types;
-they map directly to terminal and non-terminal symbols in the grammar.
-Unfortunately, they are represented as integers in the internal representation,
-and the Python structures generated do not change that. However, the
-:mod:`symbol` and :mod:`token` modules provide symbolic names for the node types
-and dictionaries which map from the integers to the symbolic names for the node
-types.
-
-In the output presented above, the outermost tuple contains four elements: the
-integer ``257`` and three additional tuples. Node type ``257`` has the symbolic
-name :const:`file_input`. Each of these inner tuples contains an integer as the
-first element; these integers, ``264``, ``4``, and ``0``, represent the node
-types :const:`stmt`, :const:`NEWLINE`, and :const:`ENDMARKER`, respectively.
-Note that these values may change depending on the version of Python you are
-using; consult :file:`symbol.py` and :file:`token.py` for details of the
-mapping. It should be fairly clear that the outermost node is related primarily
-to the input source rather than the contents of the file, and may be disregarded
-for the moment. The :const:`stmt` node is much more interesting. In
-particular, all docstrings are found in subtrees which are formed exactly as
-this node is formed, with the only difference being the string itself. The
-association between the docstring in a similar tree and the defined entity
-(class, function, or module) which it describes is given by the position of the
-docstring subtree within the tree defining the described structure.
-
-By replacing the actual docstring with something to signify a variable component
-of the tree, we allow a simple pattern matching approach to check any given
-subtree for equivalence to the general pattern for docstrings. Since the
-example demonstrates information extraction, we can safely require that the tree
-be in tuple form rather than list form, allowing a simple variable
-representation to be ``['variable_name']``. A simple recursive function can
-implement the pattern matching, returning a Boolean and a dictionary of variable
-name to value mappings. (See file :file:`example.py`.) ::
-
- from types import ListType, TupleType
-
- def match(pattern, data, vars=None):
- if vars is None:
- vars = {}
- if type(pattern) is ListType:
- vars[pattern[0]] = data
- return 1, vars
- if type(pattern) is not TupleType:
- return (pattern == data), vars
- if len(data) != len(pattern):
- return 0, vars
- for pattern, data in map(None, pattern, data):
- same, vars = match(pattern, data, vars)
- if not same:
- break
- return same, vars
-
-Using this simple representation for syntactic variables and the symbolic node
-types, the pattern for the candidate docstring subtrees becomes fairly readable.
-(See file :file:`example.py`.) ::
-
- import symbol
- import token
-
- DOCSTRING_STMT_PATTERN = (
- symbol.stmt,
- (symbol.simple_stmt,
- (symbol.small_stmt,
- (symbol.expr_stmt,
- (symbol.testlist,
- (symbol.test,
- (symbol.and_test,
- (symbol.not_test,
- (symbol.comparison,
- (symbol.expr,
- (symbol.xor_expr,
- (symbol.and_expr,
- (symbol.shift_expr,
- (symbol.arith_expr,
- (symbol.term,
- (symbol.factor,
- (symbol.power,
- (symbol.atom,
- (token.STRING, ['docstring'])
- )))))))))))))))),
- (token.NEWLINE, '')
- ))
-
-Using the :func:`match` function with this pattern, extracting the module
-docstring from the parse tree created previously is easy::
-
- >>> found, vars = match(DOCSTRING_STMT_PATTERN, tup[1])
- >>> found
- 1
- >>> vars
- {'docstring': '"""Some documentation.\n"""'}
-
-Once specific data can be extracted from a location where it is expected, the
-question of where information can be expected needs to be answered. When
-dealing with docstrings, the answer is fairly simple: the docstring is the first
-:const:`stmt` node in a code block (:const:`file_input` or :const:`suite` node
-types). A module consists of a single :const:`file_input` node, and class and
-function definitions each contain exactly one :const:`suite` node. Classes and
-functions are readily identified as subtrees of code block nodes which start
-with ``(stmt, (compound_stmt, (classdef, ...`` or ``(stmt, (compound_stmt,
-(funcdef, ...``. Note that these subtrees cannot be matched by :func:`match`
-since it does not support multiple sibling nodes to match without regard to
-number. A more elaborate matching function could be used to overcome this
-limitation, but this is sufficient for the example.
-
-Given the ability to determine whether a statement might be a docstring and
-extract the actual string from the statement, some work needs to be performed to
-walk the parse tree for an entire module and extract information about the names
-defined in each context of the module and associate any docstrings with the
-names. The code to perform this work is not complicated, but bears some
-explanation.
-
-The public interface to the classes is straightforward and should probably be
-somewhat more flexible. Each "major" block of the module is described by an
-object providing several methods for inquiry and a constructor which accepts at
-least the subtree of the complete parse tree which it represents. The
-:class:`ModuleInfo` constructor accepts an optional *name* parameter since it
-cannot otherwise determine the name of the module.
-
-The public classes include :class:`ClassInfo`, :class:`FunctionInfo`, and
-:class:`ModuleInfo`. All objects provide the methods :meth:`get_name`,
-:meth:`get_docstring`, :meth:`get_class_names`, and :meth:`get_class_info`. The
-:class:`ClassInfo` objects support :meth:`get_method_names` and
-:meth:`get_method_info` while the other classes provide
-:meth:`get_function_names` and :meth:`get_function_info`.
-
-Within each of the forms of code block that the public classes represent, most
-of the required information is in the same form and is accessed in the same way,
-with classes having the distinction that functions defined at the top level are
-referred to as "methods." Since the difference in nomenclature reflects a real
-semantic distinction from functions defined outside of a class, the
-implementation needs to maintain the distinction. Hence, most of the
-functionality of the public classes can be implemented in a common base class,
-:class:`SuiteInfoBase`, with the accessors for function and method information
-provided elsewhere. Note that there is only one class which represents function
-and method information; this parallels the use of the :keyword:`def` statement
-to define both types of elements.
-
-Most of the accessor functions are declared in :class:`SuiteInfoBase` and do not
-need to be overridden by subclasses. More importantly, the extraction of most
-information from a parse tree is handled through a method called by the
-:class:`SuiteInfoBase` constructor. The example code for most of the classes is
-clear when read alongside the formal grammar, but the method which recursively
-creates new information objects requires further examination. Here is the
-relevant part of the :class:`SuiteInfoBase` definition from :file:`example.py`::
-
- class SuiteInfoBase:
- _docstring = ''
- _name = ''
-
- def __init__(self, tree = None):
- self._class_info = {}
- self._function_info = {}
- if tree:
- self._extract_info(tree)
-
- def _extract_info(self, tree):
- # extract docstring
- if len(tree) == 2:
- found, vars = match(DOCSTRING_STMT_PATTERN[1], tree[1])
- else:
- found, vars = match(DOCSTRING_STMT_PATTERN, tree[3])
- if found:
- self._docstring = eval(vars['docstring'])
- # discover inner definitions
- for node in tree[1:]:
- found, vars = match(COMPOUND_STMT_PATTERN, node)
- if found:
- cstmt = vars['compound']
- if cstmt[0] == symbol.funcdef:
- name = cstmt[2][1]
- self._function_info[name] = FunctionInfo(cstmt)
- elif cstmt[0] == symbol.classdef:
- name = cstmt[2][1]
- self._class_info[name] = ClassInfo(cstmt)
-
-After initializing some internal state, the constructor calls the
-:meth:`_extract_info` method. This method performs the bulk of the information
-extraction which takes place in the entire example. The extraction has two
-distinct phases: the location of the docstring for the parse tree passed in, and
-the discovery of additional definitions within the code block represented by the
-parse tree.
-
-The initial :keyword:`if` test determines whether the nested suite is of the
-"short form" or the "long form." The short form is used when the code block is
-on the same line as the definition of the code block, as in ::
-
- def square(x): "Square an argument."; return x ** 2
-
-while the long form uses an indented block and allows nested definitions::
-
- def make_power(exp):
- "Make a function that raises an argument to the exponent `exp`."
- def raiser(x, y=exp):
- return x ** y
- return raiser
-
-When the short form is used, the code block may contain a docstring as the
-first, and possibly only, :const:`small_stmt` element. The extraction of such a
-docstring is slightly different and requires only a portion of the complete
-pattern used in the more common case. As implemented, the docstring will only
-be found if there is only one :const:`small_stmt` node in the
-:const:`simple_stmt` node. Since most functions and methods which use the short
-form do not provide a docstring, this may be considered sufficient. The
-extraction of the docstring proceeds using the :func:`match` function as
-described above, and the value of the docstring is stored as an attribute of the
-:class:`SuiteInfoBase` object.
-
-After docstring extraction, a simple definition discovery algorithm operates on
-the :const:`stmt` nodes of the :const:`suite` node. The special case of the
-short form is not tested; since there are no :const:`stmt` nodes in the short
-form, the algorithm will silently skip the single :const:`simple_stmt` node and
-correctly not discover any nested definitions.
-
-Each statement in the code block is categorized as a class definition, function
-or method definition, or something else. For the definition statements, the
-name of the element defined is extracted and a representation object appropriate
-to the definition is created with the defining subtree passed as an argument to
-the constructor. The representation objects are stored in instance variables
-and may be retrieved by name using the appropriate accessor methods.
-
-The public classes provide any accessors required which are more specific than
-those provided by the :class:`SuiteInfoBase` class, but the real extraction
-algorithm remains common to all forms of code blocks. A high-level function can
-be used to extract the complete set of information from a source file. (See
-file :file:`example.py`.) ::
-
- def get_docs(fileName):
- import os
- import parser
-
- source = open(fileName).read()
- basename = os.path.basename(os.path.splitext(fileName)[0])
- st = parser.suite(source)
- return ModuleInfo(st.totuple(), basename)
-
-This provides an easy-to-use interface to the documentation of a module. If
-information is required which is not extracted by the code of this example, the
-code may be extended at clearly defined points to provide additional
-capabilities.
-
Modified: python/branches/release27-maint/Doc/library/pickle.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/pickle.rst (original)
+++ python/branches/release27-maint/Doc/library/pickle.rst Fri Nov 26 08:53:50 2010
@@ -25,6 +25,12 @@
This documentation describes both the :mod:`pickle` module and the
:mod:`cPickle` module.
+.. warning::
+
+ The :mod:`pickle` module is not intended to be secure against erroneous or
+ maliciously constructed data. Never unpickle data received from an untrusted
+ or unauthenticated source.
+
Relationship to other Python modules
------------------------------------
@@ -74,12 +80,6 @@
The :mod:`pickle` serialization format is guaranteed to be backwards compatible
across Python releases.
-.. warning::
-
- The :mod:`pickle` module is not intended to be secure against erroneous or
- maliciously constructed data. Never unpickle data received from an untrusted
- or unauthenticated source.
-
Note that serialization is a more primitive notion than persistence; although
:mod:`pickle` reads and writes file objects, it does not handle the issue of
naming persistent objects, nor the (even more complicated) issue of concurrent
Modified: python/branches/release27-maint/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/stdtypes.rst (original)
+++ python/branches/release27-maint/Doc/library/stdtypes.rst Fri Nov 26 08:53:50 2010
@@ -1944,15 +1944,12 @@
values are added as items to the dictionary. If a key is specified both in the
positional argument and as a keyword argument, the value associated with the
keyword is retained in the dictionary. For example, these all return a
- dictionary equal to ``{"one": 2, "two": 3}``:
+ dictionary equal to ``{"one": 1, "two": 2}``:
- * ``dict(one=2, two=3)``
-
- * ``dict({'one': 2, 'two': 3})``
-
- * ``dict(zip(('one', 'two'), (2, 3)))``
-
- * ``dict([['two', 3], ['one', 2]])``
+ * ``dict(one=1, two=2)``
+ * ``dict({'one': 1, 'two': 2})``
+ * ``dict(zip(('one', 'two'), (1, 2)))``
+ * ``dict([['two', 2], ['one', 1]])``
The first example only works for keys that are valid Python
identifiers; the others work with any valid keys.
Modified: python/branches/release27-maint/Doc/library/sys.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/sys.rst (original)
+++ python/branches/release27-maint/Doc/library/sys.rst Fri Nov 26 08:53:50 2010
@@ -53,6 +53,13 @@
``modules.keys()`` only lists the imported modules.)
+.. function:: call_tracing(func, args)
+
+ Call ``func(*args)``, while tracing is enabled. The tracing state is saved,
+ and restored afterwards. This is intended to be called from a debugger from
+ a checkpoint, to recursively debug some other code.
+
+
.. data:: copyright
A string containing the copyright pertaining to the Python interpreter.
@@ -219,19 +226,25 @@
Exit from Python. This is implemented by raising the :exc:`SystemExit`
exception, so cleanup actions specified by finally clauses of :keyword:`try`
- statements are honored, and it is possible to intercept the exit attempt at an
- outer level. The optional argument *arg* can be an integer giving the exit
- status (defaulting to zero), or another type of object. If it is an integer,
- zero is considered "successful termination" and any nonzero value is considered
- "abnormal termination" by shells and the like. Most systems require it to be in
- the range 0-127, and produce undefined results otherwise. Some systems have a
- convention for assigning specific meanings to specific exit codes, but these are
- generally underdeveloped; Unix programs generally use 2 for command line syntax
- errors and 1 for all other kind of errors. If another type of object is passed,
- ``None`` is equivalent to passing zero, and any other object is printed to
- ``sys.stderr`` and results in an exit code of 1. In particular,
- ``sys.exit("some error message")`` is a quick way to exit a program when an
- error occurs.
+ statements are honored, and it is possible to intercept the exit attempt at
+ an outer level.
+
+ The optional argument *arg* can be an integer giving the exit status
+ (defaulting to zero), or another type of object. If it is an integer, zero
+ is considered "successful termination" and any nonzero value is considered
+ "abnormal termination" by shells and the like. Most systems require it to be
+ in the range 0-127, and produce undefined results otherwise. Some systems
+ have a convention for assigning specific meanings to specific exit codes, but
+ these are generally underdeveloped; Unix programs generally use 2 for command
+ line syntax errors and 1 for all other kind of errors. If another type of
+ object is passed, ``None`` is equivalent to passing zero, and any other
+ object is printed to :data:`stderr` and results in an exit code of 1. In
+ particular, ``sys.exit("some error message")`` is a quick way to exit a
+ program when an error occurs.
+
+ Since :func:`exit` ultimately "only" raises an exception, it will only exit
+ the process when called from the main thread, and the exception is not
+ intercepted.
.. data:: exitfunc
Modified: python/branches/release27-maint/Doc/tutorial/classes.rst
==============================================================================
--- python/branches/release27-maint/Doc/tutorial/classes.rst (original)
+++ python/branches/release27-maint/Doc/tutorial/classes.rst Fri Nov 26 08:53:50 2010
@@ -4,25 +4,26 @@
Classes
*******
-Python's class mechanism adds classes to the language with a minimum of new
-syntax and semantics. It is a mixture of the class mechanisms found in C++ and
-Modula-3. As is true for modules, classes in Python do not put an absolute
-barrier between definition and user, but rather rely on the politeness of the
-user not to "break into the definition." The most important features of classes
-are retained with full power, however: the class inheritance mechanism allows
+Compared with other programming languages, Python's class mechanism adds classes
+with a minimum of new syntax and semantics. It is a mixture of the class
+mechanisms found in C++ and Modula-3. Python classes provide all the standard
+features of Object Oriented Programming: the class inheritance mechanism allows
multiple base classes, a derived class can override any methods of its base
class or classes, and a method can call the method of a base class with the same
-name. Objects can contain an arbitrary amount of data.
-
-In C++ terminology, all class members (including the data members) are *public*,
-and all member functions are *virtual*. As in Modula-3, there are no shorthands
-for referencing the object's members from its methods: the method function is
-declared with an explicit first argument representing the object, which is
-provided implicitly by the call. As in Smalltalk, classes themselves are
-objects. This provides semantics for importing and renaming. Unlike C++ and
-Modula-3, built-in types can be used as base classes for extension by the user.
-Also, like in C++, most built-in operators with special syntax (arithmetic
-operators, subscripting etc.) can be redefined for class instances.
+name. Objects can contain arbitrary amounts and kinds of data. As is true for
+modules, classes partake of the dynamic nature of Python: they are created at
+runtime, and can be modified further after creation.
+
+In C++ terminology, normally class members (including the data members) are
+*public* (except see below :ref:`tut-private`), and all member functions are
+*virtual*. As in Modula-3, there are no shorthands for referencing the object's
+members from its methods: the method function is declared with an explicit first
+argument representing the object, which is provided implicitly by the call. As
+in Smalltalk, classes themselves are objects. This provides semantics for
+importing and renaming. Unlike C++ and Modula-3, built-in types can be used as
+base classes for extension by the user. Also, like in C++, most built-in
+operators with special syntax (arithmetic operators, subscripting etc.) can be
+redefined for class instances.
(Lacking universally accepted terminology to talk about classes, I will make
occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, since
1
0
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 08:42:15 2010
New Revision: 86767
Log:
Merged revisions 85548,85572-85573,85606,85609-85612,85614-85616 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85548 | georg.brandl | 2010-10-15 21:46:19 +0200 (Fr, 15 Okt 2010) | 1 line
#10072: assume a bit less knowledge of the FTP protocol in the ftplib docs.
........
r85572 | georg.brandl | 2010-10-16 20:51:05 +0200 (Sa, 16 Okt 2010) | 1 line
#10122: typo fix.
........
r85573 | georg.brandl | 2010-10-16 20:53:08 +0200 (Sa, 16 Okt 2010) | 1 line
#10124: typo fix.
........
r85606 | georg.brandl | 2010-10-17 08:32:59 +0200 (So, 17 Okt 2010) | 1 line
#10058: tweak wording about exception returns.
........
r85609 | georg.brandl | 2010-10-17 11:19:03 +0200 (So, 17 Okt 2010) | 1 line
#8556: use less confusing mapping key in example.
........
r85610 | georg.brandl | 2010-10-17 11:23:05 +0200 (So, 17 Okt 2010) | 1 line
#8686: remove potentially confusing wording that does not add any value.
........
r85611 | georg.brandl | 2010-10-17 11:33:24 +0200 (So, 17 Okt 2010) | 1 line
#8811: small fixes to sqlite3 docs.
........
r85612 | georg.brandl | 2010-10-17 11:37:54 +0200 (So, 17 Okt 2010) | 1 line
#8855: add shelve security warning.
........
r85614 | georg.brandl | 2010-10-17 11:46:11 +0200 (So, 17 Okt 2010) | 1 line
#8968: add actual name of token constants.
........
r85615 | georg.brandl | 2010-10-17 12:05:13 +0200 (So, 17 Okt 2010) | 1 line
#459007: merge info from PC/getpathp.c and using/windows.rst to document the forming of sys.path under Windows.
........
r85616 | georg.brandl | 2010-10-17 12:07:29 +0200 (So, 17 Okt 2010) | 1 line
Fix copy-paste error in example.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Doc/c-api/intro.rst
python/branches/release27-maint/Doc/howto/cporting.rst
python/branches/release27-maint/Doc/library/audioop.rst
python/branches/release27-maint/Doc/library/difflib.rst
python/branches/release27-maint/Doc/library/ftplib.rst
python/branches/release27-maint/Doc/library/functions.rst
python/branches/release27-maint/Doc/library/shelve.rst
python/branches/release27-maint/Doc/library/sqlite3.rst
python/branches/release27-maint/Doc/library/stdtypes.rst
python/branches/release27-maint/Doc/library/token.rst
python/branches/release27-maint/Doc/using/windows.rst
Modified: python/branches/release27-maint/Doc/c-api/intro.rst
==============================================================================
--- python/branches/release27-maint/Doc/c-api/intro.rst (original)
+++ python/branches/release27-maint/Doc/c-api/intro.rst Fri Nov 26 08:42:15 2010
@@ -361,15 +361,16 @@
.. index:: single: PyErr_Occurred()
-For C programmers, however, error checking always has to be explicit. All
-functions in the Python/C API can raise exceptions, unless an explicit claim is
-made otherwise in a function's documentation. In general, when a function
-encounters an error, it sets an exception, discards any object references that
-it owns, and returns an error indicator --- usually *NULL* or ``-1``. A few
-functions return a Boolean true/false result, with false indicating an error.
-Very few functions return no explicit error indicator or have an ambiguous
-return value, and require explicit testing for errors with
-:cfunc:`PyErr_Occurred`.
+For C programmers, however, error checking always has to be explicit. All
+functions in the Python/C API can raise exceptions, unless an explicit claim is
+made otherwise in a function's documentation. In general, when a function
+encounters an error, it sets an exception, discards any object references that
+it owns, and returns an error indicator. If not documented otherwise, this
+indicator is either *NULL* or ``-1``, depending on the function's return type.
+A few functions return a Boolean true/false result, with false indicating an
+error. Very few functions return no explicit error indicator or have an
+ambiguous return value, and require explicit testing for errors with
+:cfunc:`PyErr_Occurred`. These exceptions are always explicitly documented.
.. index::
single: PyErr_SetString()
Modified: python/branches/release27-maint/Doc/howto/cporting.rst
==============================================================================
--- python/branches/release27-maint/Doc/howto/cporting.rst (original)
+++ python/branches/release27-maint/Doc/howto/cporting.rst Fri Nov 26 08:42:15 2010
@@ -48,9 +48,9 @@
compatibility with 3.0, :ctype:`PyUnicode` should be used for textual data and
:ctype:`PyBytes` for binary data. It's also important to remember that
:ctype:`PyBytes` and :ctype:`PyUnicode` in 3.0 are not interchangeable like
-:ctype:`PyString` and :ctype:`PyString` are in 2.x. The following example shows
-best practices with regards to :ctype:`PyUnicode`, :ctype:`PyString`, and
-:ctype:`PyBytes`. ::
+:ctype:`PyString` and :ctype:`PyUnicode` are in 2.x. The following example
+shows best practices with regards to :ctype:`PyUnicode`, :ctype:`PyString`,
+and :ctype:`PyBytes`. ::
#include "stdlib.h"
#include "Python.h"
Modified: python/branches/release27-maint/Doc/library/audioop.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/audioop.rst (original)
+++ python/branches/release27-maint/Doc/library/audioop.rst Fri Nov 26 08:42:15 2010
@@ -236,8 +236,8 @@
def mul_stereo(sample, width, lfactor, rfactor):
lsample = audioop.tomono(sample, width, 1, 0)
rsample = audioop.tomono(sample, width, 0, 1)
- lsample = audioop.mul(sample, width, lfactor)
- rsample = audioop.mul(sample, width, rfactor)
+ lsample = audioop.mul(lsample, width, lfactor)
+ rsample = audioop.mul(rsample, width, rfactor)
lsample = audioop.tostereo(lsample, width, 1, 0)
rsample = audioop.tostereo(rsample, width, 0, 1)
return audioop.add(lsample, rsample, width)
Modified: python/branches/release27-maint/Doc/library/difflib.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/difflib.rst (original)
+++ python/branches/release27-maint/Doc/library/difflib.rst Fri Nov 26 08:42:15 2010
@@ -528,16 +528,11 @@
Return an upper bound on :meth:`ratio` relatively quickly.
- This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
- is faster to compute.
-
.. method:: real_quick_ratio()
Return an upper bound on :meth:`ratio` very quickly.
- This isn't defined beyond that it is an upper bound on :meth:`ratio`, and
- is faster to compute than either :meth:`ratio` or :meth:`quick_ratio`.
The three methods that return the ratio of matching to total characters can give
different results due to differing levels of approximation, although
Modified: python/branches/release27-maint/Doc/library/ftplib.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/ftplib.rst (original)
+++ python/branches/release27-maint/Doc/library/ftplib.rst Fri Nov 26 08:42:15 2010
@@ -91,18 +91,21 @@
.. exception:: error_temp
- Exception raised when an error code in the range 400--499 is received.
+ Exception raised when an error code signifying a temporary error (response
+ codes in the range 400--499) is received.
.. exception:: error_perm
- Exception raised when an error code in the range 500--599 is received.
+ Exception raised when an error code signifying a permanent error (response
+ codes in the range 500--599) is received.
.. exception:: error_proto
- Exception raised when a reply is received from the server that does not
- begin with a digit in the range 1--5.
+ Exception raised when a reply is received from the server that does not fit
+ the response specifications of the File Transfer Protocol, i.e. begin with a
+ digit in the range 1--5.
.. data:: all_errors
@@ -198,9 +201,9 @@
.. method:: FTP.voidcmd(command)
- Send a simple command string to the server and handle the response. Return
- nothing if a response code in the range 200--299 is received. Raise an exception
- otherwise.
+ Send a simple command string to the server and handle the response. Return
+ nothing if a response code corresponding to success (codes in the range
+ 200--299) is received. Raise :exc:`error_reply` otherwise.
.. method:: FTP.retrbinary(command, callback[, maxblocksize[, rest]])
@@ -220,9 +223,11 @@
Retrieve a file or directory listing in ASCII transfer mode. *command*
should be an appropriate ``RETR`` command (see :meth:`retrbinary`) or a
command such as ``LIST``, ``NLST`` or ``MLSD`` (usually just the string
- ``'LIST'``). The *callback* function is called for each line with a
- string argument containing the line with the trailing CRLF stripped.
- The default *callback* prints the line to ``sys.stdout``.
+ ``'LIST'``). ``LIST`` retrieves a list of files and information about those files.
+ ``NLST`` retrieves a list of file names. On some servers, ``MLSD`` retrieves
+ a machine readable list of files and information about those files. The *callback*
+ function is called for each line with a string argument containing the line with
+ the trailing CRLF stripped. The default *callback* prints the line to ``sys.stdout``.
.. method:: FTP.set_pasv(boolean)
@@ -293,10 +298,10 @@
.. method:: FTP.nlst(argument[, ...])
- Return a list of files as returned by the ``NLST`` command. The optional
- *argument* is a directory to list (default is the current server directory).
- Multiple arguments can be used to pass non-standard options to the ``NLST``
- command.
+ Return a list of file names as returned by the ``NLST`` command. The
+ optional *argument* is a directory to list (default is the current server
+ directory). Multiple arguments can be used to pass non-standard options to
+ the ``NLST`` command.
.. method:: FTP.dir(argument[, ...])
Modified: python/branches/release27-maint/Doc/library/functions.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/functions.rst (original)
+++ python/branches/release27-maint/Doc/library/functions.rst Fri Nov 26 08:42:15 2010
@@ -514,7 +514,7 @@
.. function:: getattr(object, name[, default])
- Return the value of the named attributed of *object*. *name* must be a string.
+ Return the value of the named attribute of *object*. *name* must be a string.
If the string is the name of one of the object's attributes, the result is the
value of that attribute. For example, ``getattr(x, 'foobar')`` is equivalent to
``x.foobar``. If the named attribute does not exist, *default* is returned if
Modified: python/branches/release27-maint/Doc/library/shelve.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/shelve.rst (original)
+++ python/branches/release27-maint/Doc/library/shelve.rst Fri Nov 26 08:42:15 2010
@@ -50,6 +50,11 @@
:meth:`close` explicitly when you don't need it any more, or use a
:keyword:`with` statement with :func:`contextlib.closing`.
+.. warning::
+
+ Because the :mod:`shelve` module is backed by :mod:`pickle`, it is insecure
+ to load a shelf from an untrusted source. Like with pickle, loading a shelf
+ can execute arbitrary code.
Shelf objects support all methods supported by dictionaries. This eases the
transition from dictionary based scripts to those requiring persistent storage.
Modified: python/branches/release27-maint/Doc/library/sqlite3.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/sqlite3.rst (original)
+++ python/branches/release27-maint/Doc/library/sqlite3.rst Fri Nov 26 08:42:15 2010
@@ -258,22 +258,21 @@
.. method:: Connection.execute(sql, [parameters])
This is a nonstandard shortcut that creates an intermediate cursor object by
- calling the cursor method, then calls the cursor's
- :meth:`execute<Cursor.execute>` method with the parameters given.
+ calling the cursor method, then calls the cursor's :meth:`execute
+ <Cursor.execute>` method with the parameters given.
.. method:: Connection.executemany(sql, [parameters])
This is a nonstandard shortcut that creates an intermediate cursor object by
- calling the cursor method, then calls the cursor's
- :meth:`executemany<Cursor.executemany>` method with the parameters given.
+ calling the cursor method, then calls the cursor's :meth:`executemany
+ <Cursor.executemany>` method with the parameters given.
.. method:: Connection.executescript(sql_script)
This is a nonstandard shortcut that creates an intermediate cursor object by
- calling the cursor method, then calls the cursor's
- :meth:`executescript<Cursor.executescript>` method with the parameters
- given.
+ calling the cursor method, then calls the cursor's :meth:`executescript
+ <Cursor.executescript>` method with the parameters given.
.. method:: Connection.create_function(name, num_params, func)
@@ -374,7 +373,7 @@
This routine allows/disallows the SQLite engine to load SQLite extensions
from shared libraries. SQLite extensions can define new functions,
- aggregates or whole new virtual table implementations. One well-known
+ aggregates or whole new virtual table implementations. One well-known
extension is the fulltext-search extension distributed with SQLite.
.. literalinclude:: ../includes/sqlite3/load_extension.py
@@ -383,9 +382,9 @@
.. versionadded:: 2.7
- This routine loads a SQLite extension from a shared library. You have to
- enable extension loading with ``enable_load_extension`` before you can use
- this routine.
+ This routine loads a SQLite extension from a shared library. You have to
+ enable extension loading with :meth:`enable_load_extension` before you can
+ use this routine.
.. attribute:: Connection.row_factory
@@ -458,9 +457,9 @@
Cursor Objects
--------------
-A :class:`Cursor` instance has the following attributes and methods:
+.. class:: Cursor
- A SQLite database cursor has the following attributes and methods:
+ A :class:`Cursor` instance has the following attributes and methods.
.. method:: Cursor.execute(sql, [parameters])
@@ -894,4 +893,3 @@
The only exception is calling the :meth:`~Connection.interrupt` method, which
only makes sense to call from a different thread.
-
Modified: python/branches/release27-maint/Doc/library/stdtypes.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/stdtypes.rst (original)
+++ python/branches/release27-maint/Doc/library/stdtypes.rst Fri Nov 26 08:42:15 2010
@@ -1356,8 +1356,8 @@
dictionary inserted immediately after the ``'%'`` character. The mapping key
selects the value to be formatted from the mapping. For example:
- >>> print '%(language)s has %(#)03d quote types.' % \
- ... {'language': "Python", "#": 2}
+ >>> print '%(language)s has %(number)03d quote types.' % \
+ ... {"language": "Python", "number": 2}
Python has 002 quote types.
In this case no ``*`` specifiers may occur in a format (since they require a
Modified: python/branches/release27-maint/Doc/library/token.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/token.rst (original)
+++ python/branches/release27-maint/Doc/library/token.rst Fri Nov 26 08:42:15 2010
@@ -13,8 +13,8 @@
the language grammar. The specific numeric values which the names map to may
change between Python versions.
-This module also provides one data object and some functions. The functions
-mirror definitions in the Python C header files.
+The module also provides a mapping from numeric codes to names and some
+functions. The functions mirror definitions in the Python C header files.
.. data:: tok_name
@@ -39,6 +39,65 @@
Return true if *x* is the marker indicating the end of input.
+The token constants are:
+
+.. data:: ENDMARKER
+ NAME
+ NUMBER
+ STRING
+ NEWLINE
+ INDENT
+ DEDENT
+ LPAR
+ RPAR
+ LSQB
+ RSQB
+ COLON
+ COMMA
+ SEMI
+ PLUS
+ MINUS
+ STAR
+ SLASH
+ VBAR
+ AMPER
+ LESS
+ GREATER
+ EQUAL
+ DOT
+ PERCENT
+ BACKQUOTE
+ LBRACE
+ RBRACE
+ EQEQUAL
+ NOTEQUAL
+ LESSEQUAL
+ GREATEREQUAL
+ TILDE
+ CIRCUMFLEX
+ LEFTSHIFT
+ RIGHTSHIFT
+ DOUBLESTAR
+ PLUSEQUAL
+ MINEQUAL
+ STAREQUAL
+ SLASHEQUAL
+ PERCENTEQUAL
+ AMPEREQUAL
+ VBAREQUAL
+ CIRCUMFLEXEQUAL
+ LEFTSHIFTEQUAL
+ RIGHTSHIFTEQUAL
+ DOUBLESTAREQUAL
+ DOUBLESLASH
+ DOUBLESLASHEQUAL
+ AT
+ OP
+ ERRORTOKEN
+ N_TOKENS
+ NT_OFFSET
+
+
.. seealso::
Module :mod:`parser`
Modified: python/branches/release27-maint/Doc/using/windows.rst
==============================================================================
--- python/branches/release27-maint/Doc/using/windows.rst (original)
+++ python/branches/release27-maint/Doc/using/windows.rst Fri Nov 26 08:42:15 2010
@@ -158,23 +158,48 @@
:file:`C:\\Python\\Lib\\` and third-party modules should be stored in
:file:`C:\\Python\\Lib\\site-packages\\`.
-.. `` this fixes syntax highlighting errors in some editors due to the \\ hackery
+This is how :data:`sys.path` is populated on Windows:
-You can add folders to your search path to make Python's import mechanism search
-in these directories as well. Use :envvar:`PYTHONPATH`, as described in
-:ref:`using-on-envvars`, to modify :data:`sys.path`. On Windows, paths are
-separated by semicolons, though, to distinguish them from drive identifiers
-(:file:`C:\\` etc.).
-
-.. ``
-
-Modifying the module search path can also be done through the Windows registry
-under the key :file:`HKLM\\SOFTWARE\\Python\\PythonCore\\{version}\\PythonPath`.
-Subkeys which have semicolon-delimited path strings as their default value will
-cause each path to be searched. Multiple subkeys can be created and are
-appended to the path in alphabetical order. A convenient registry editor is
-:program:`regedit` (start it by typing "regedit" into :menuselection:`Start -->
-Run`).
+* An empty entry is added at the start, which corresponds to the current
+ directory.
+
+* If the environment variable :envvar:`PYTHONPATH` exists, as described in
+ :ref:`using-on-envvars`, its entries are added next. Note that on Windows,
+ paths in this variable must be separated by semicolons, to distinguish them
+ from the colon used in drive identifiers (``C:\`` etc.).
+
+* Additional "application paths" can be added in the registry as subkeys of
+ :samp:`\\SOFTWARE\\Python\\PythonCore\\{version}\\PythonPath` under both the
+ ``HKEY_CURRENT_USER`` and ``HKEY_LOCAL_MACHINE`` hives. Subkeys which have
+ semicolon-delimited path strings as their default value will cause each path
+ to be added to :data:`sys.path`. (Note that all known installers only use
+ HKLM, so HKCU is typically empty.)
+
+* If the environment variable :envvar:`PYTHONHOME` is set, it is assumed as
+ "Python Home". Otherwise, the path of the main Python executable is used to
+ locate a "landmark file" (``Lib\os.py``) to deduce the "Python Home". If a
+ Python home is found, the relevant sub-directories added to :data:`sys.path`
+ (``Lib``, ``plat-win``, etc) are based on that folder. Otherwise, the core
+ Python path is constructed from the PythonPath stored in the registry.
+
+* If the Python Home cannot be located, no :envvar:`PYTHONPATH` is specified in
+ the environment, and no registry entries can be found, a default path with
+ relative entries is used (e.g. ``.\Lib;.\plat-win``, etc).
+
+The end result of all this is:
+
+* When running :file:`python.exe`, or any other .exe in the main Python
+ directory (either an installed version, or directly from the PCbuild
+ directory), the core path is deduced, and the core paths in the registry are
+ ignored. Other "application paths" in the registry are always read.
+
+* When Python is hosted in another .exe (different directory, embedded via COM,
+ etc), the "Python Home" will not be deduced, so the core path from the
+ registry is used. Other "application paths" in the registry are always read.
+
+* If Python can't find its home and there is no registry (eg, frozen .exe, some
+ very strange installation setup) you get a path with some default, but
+ relative, paths.
Executing scripts
1
0
Author: georg.brandl
Date: Fri Nov 26 08:36:32 2010
New Revision: 86766
Log:
Blocked revisions 85526,85528,85531-85533,85535,85539 via svnmerge
........
r85526 | georg.brandl | 2010-10-15 16:46:48 +0200 (Fr, 15 Okt 2010) | 1 line
#5355: Provide mappings from Expat error numbers to string descriptions and backwards, in order to actually make it possible to analyze error codes provided by ExpatError.
........
r85528 | georg.brandl | 2010-10-15 17:25:23 +0200 (Fr, 15 Okt 2010) | 1 line
#5355 followup: add unit test for new dictionaries, and provide submodules from xml.parsers.expat as advertised.
........
r85531 | georg.brandl | 2010-10-15 17:57:45 +0200 (Fr, 15 Okt 2010) | 1 line
#2830: add html.escape() helper and move cgi.escape() uses in the standard library to it. It defaults to quote=True and also escapes single quotes, which makes casual use safer. The cgi.escape() interface is not touched, but emits a (silent) PendingDeprecationWarning.
........
r85532 | georg.brandl | 2010-10-15 18:03:02 +0200 (Fr, 15 Okt 2010) | 1 line
#7771: reference to documentation of dictview methods and operations.
........
r85533 | georg.brandl | 2010-10-15 18:07:41 +0200 (Fr, 15 Okt 2010) | 1 line
#9683: remove broken dead code dealing with nested arguments removed from Py3k, and update the docs and docstrings accordingly.
........
r85535 | georg.brandl | 2010-10-15 18:23:54 +0200 (Fr, 15 Okt 2010) | 1 line
Remove unused label.
........
r85539 | georg.brandl | 2010-10-15 18:42:14 +0200 (Fr, 15 Okt 2010) | 1 line
Fix issue references.
........
Modified:
python/branches/release27-maint/ (props changed)
1
0
r86765 - in python/branches/release27-maint: Lib/test/test_minidom.py Lib/xml/dom/minidom.py Misc/NEWS
by georg.brandl Nov. 26, 2010
by georg.brandl Nov. 26, 2010
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 08:35:31 2010
New Revision: 86765
Log:
Merged revisions 85546-85547 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85546 | georg.brandl | 2010-10-15 19:58:45 +0200 (Fr, 15 Okt 2010) | 1 line
#5762: fix handling of empty namespace in minidom, which would result in AttributeError on toxml().
........
r85547 | georg.brandl | 2010-10-15 20:00:35 +0200 (Fr, 15 Okt 2010) | 1 line
#6098: Refrain from claiming DOM level 3 conformance in minidom.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Lib/test/test_minidom.py
python/branches/release27-maint/Lib/xml/dom/minidom.py
python/branches/release27-maint/Misc/NEWS
Modified: python/branches/release27-maint/Lib/test/test_minidom.py
==============================================================================
--- python/branches/release27-maint/Lib/test/test_minidom.py (original)
+++ python/branches/release27-maint/Lib/test/test_minidom.py Fri Nov 26 08:35:31 2010
@@ -1483,6 +1483,13 @@
doc.appendChild(doc.createComment("foo--bar"))
self.assertRaises(ValueError, doc.toxml)
+ def testEmptyXMLNSValue(self):
+ doc = parseString("<element xmlns=''>\n"
+ "<foo/>\n</element>")
+ doc2 = parseString(doc.toxml())
+ self.confirm(doc2.namespaceURI == xml.dom.EMPTY_NAMESPACE)
+
+
def test_main():
run_unittest(MinidomTest)
Modified: python/branches/release27-maint/Lib/xml/dom/minidom.py
==============================================================================
--- python/branches/release27-maint/Lib/xml/dom/minidom.py (original)
+++ python/branches/release27-maint/Lib/xml/dom/minidom.py Fri Nov 26 08:35:31 2010
@@ -291,9 +291,10 @@
def _write_data(writer, data):
"Writes datachars to writer."
- data = data.replace("&", "&").replace("<", "<")
- data = data.replace("\"", """).replace(">", ">")
- writer.write(data)
+ if data:
+ data = data.replace("&", "&").replace("<", "<"). \
+ replace("\"", """).replace(">", ">")
+ writer.write(data)
def _get_elements_by_tagName_helper(parent, name, rc):
for node in parent.childNodes:
@@ -1340,11 +1341,9 @@
class DOMImplementation(DOMImplementationLS):
_features = [("core", "1.0"),
("core", "2.0"),
- ("core", "3.0"),
("core", None),
("xml", "1.0"),
("xml", "2.0"),
- ("xml", "3.0"),
("xml", None),
("ls-load", "3.0"),
("ls-load", None),
Modified: python/branches/release27-maint/Misc/NEWS
==============================================================================
--- python/branches/release27-maint/Misc/NEWS (original)
+++ python/branches/release27-maint/Misc/NEWS Fri Nov 26 08:35:31 2010
@@ -15,6 +15,11 @@
- Issue #10459: Update CJK character names to Unicode 5.2.
+- Issue #6098: Don't claim DOM level 3 conformance in minidom.
+
+- Issue #5762: Fix AttributeError raised by ``xml.dom.minidom`` when an empty
+ XML namespace attribute is encountered.
+
- Issue #1710703: Write structures for an empty ZIP archive when a ZipFile is
created in modes 'a' or 'w' and then closed without adding any files. Raise
BadZipfile (rather than IOError) when opening small non-ZIP files.
1
0
r86764 - in python/branches/release27-maint: Doc/c-api/init.rst Doc/library/inspect.rst Doc/library/multiprocessing.rst Doc/library/pkgutil.rst Doc/library/sys.rst Doc/library/time.rst Doc/tutorial/controlflow.rst
by georg.brandl Nov. 26, 2010
by georg.brandl Nov. 26, 2010
Nov. 26, 2010
Author: georg.brandl
Date: Fri Nov 26 08:34:20 2010
New Revision: 86764
Log:
Merged revisions 85530,85534,85538,85540-85542 via svnmerge from
svn+ssh://pythondev@svn.python.org/python/branches/py3k
........
r85530 | georg.brandl | 2010-10-15 17:32:05 +0200 (Fr, 15 Okt 2010) | 1 line
Refrain from using inline suites.
........
r85534 | georg.brandl | 2010-10-15 18:19:43 +0200 (Fr, 15 Okt 2010) | 1 line
#9801: document how list and dict proxies created by Managers behave w.r.t. mutable items.
........
r85538 | georg.brandl | 2010-10-15 18:35:46 +0200 (Fr, 15 Okt 2010) | 1 line
#7303: add documentation for useful pkgutil functions and classes.
........
r85540 | georg.brandl | 2010-10-15 18:42:37 +0200 (Fr, 15 Okt 2010) | 1 line
#6798: fix wrong docs for the arguments to several trace events.
........
r85541 | georg.brandl | 2010-10-15 18:53:24 +0200 (Fr, 15 Okt 2010) | 1 line
#4968: updates to inspect.is* function docs.
........
r85542 | georg.brandl | 2010-10-15 19:01:15 +0200 (Fr, 15 Okt 2010) | 1 line
#7790: move table of struct_time members to the actual description of struct_time.
........
Modified:
python/branches/release27-maint/ (props changed)
python/branches/release27-maint/Doc/c-api/init.rst
python/branches/release27-maint/Doc/library/inspect.rst
python/branches/release27-maint/Doc/library/multiprocessing.rst
python/branches/release27-maint/Doc/library/pkgutil.rst
python/branches/release27-maint/Doc/library/sys.rst
python/branches/release27-maint/Doc/library/time.rst
python/branches/release27-maint/Doc/tutorial/controlflow.rst
Modified: python/branches/release27-maint/Doc/c-api/init.rst
==============================================================================
--- python/branches/release27-maint/Doc/c-api/init.rst (original)
+++ python/branches/release27-maint/Doc/c-api/init.rst Fri Nov 26 08:34:20 2010
@@ -925,13 +925,14 @@
+------------------------------+--------------------------------------+
| :const:`PyTrace_LINE` | Always *NULL*. |
+------------------------------+--------------------------------------+
- | :const:`PyTrace_RETURN` | Value being returned to the caller. |
+ | :const:`PyTrace_RETURN` | Value being returned to the caller, |
+ | | or *NULL* if caused by an exception. |
+------------------------------+--------------------------------------+
- | :const:`PyTrace_C_CALL` | Name of function being called. |
+ | :const:`PyTrace_C_CALL` | Function object being called. |
+------------------------------+--------------------------------------+
- | :const:`PyTrace_C_EXCEPTION` | Always *NULL*. |
+ | :const:`PyTrace_C_EXCEPTION` | Function object being called. |
+------------------------------+--------------------------------------+
- | :const:`PyTrace_C_RETURN` | Always *NULL*. |
+ | :const:`PyTrace_C_RETURN` | Function object being called. |
+------------------------------+--------------------------------------+
Modified: python/branches/release27-maint/Doc/library/inspect.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/inspect.rst (original)
+++ python/branches/release27-maint/Doc/library/inspect.rst Fri Nov 26 08:34:20 2010
@@ -263,17 +263,20 @@
.. function:: isclass(object)
- Return true if the object is a class.
+ Return true if the object is a class, whether built-in or created in Python
+ code.
.. function:: ismethod(object)
- Return true if the object is a method.
+ Return true if the object is a bound method written in Python.
.. function:: isfunction(object)
- Return true if the object is a Python function or unnamed (:term:`lambda`) function.
+ Return true if the object is a Python function, which includes functions
+ created by a :term:`lambda` expression.
+
.. function:: isgeneratorfunction(object)
@@ -281,12 +284,14 @@
.. versionadded:: 2.6
+
.. function:: isgenerator(object)
Return true if the object is a generator.
.. versionadded:: 2.6
+
.. function:: istraceback(object)
Return true if the object is a traceback.
@@ -304,13 +309,14 @@
.. function:: isbuiltin(object)
- Return true if the object is a built-in function.
+ Return true if the object is a built-in function or a bound built-in method.
.. function:: isroutine(object)
Return true if the object is a user-defined or built-in function or method.
+
.. function:: isabstract(object)
Return true if the object is an abstract base class.
@@ -320,8 +326,9 @@
.. function:: ismethoddescriptor(object)
- Return true if the object is a method descriptor, but not if :func:`ismethod`
- or :func:`isclass` or :func:`isfunction` are true.
+ Return true if the object is a method descriptor, but not if
+ :func:`ismethod`, :func:`isclass`, :func:`isfunction` or :func:`isbuiltin`
+ are true.
This is new as of Python 2.2, and, for example, is true of
``int.__add__``. An object passing this test has a :attr:`__get__` attribute
Modified: python/branches/release27-maint/Doc/library/multiprocessing.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/multiprocessing.rst (original)
+++ python/branches/release27-maint/Doc/library/multiprocessing.rst Fri Nov 26 08:34:20 2010
@@ -1286,6 +1286,24 @@
Create a shared ``list`` object and return a proxy for it.
+ .. note::
+
+ Modifications to mutable values or items in dict and list proxies will not
+ be propagated through the manager, because the proxy has no way of knowing
+ when its values or items are modified. To modify such an item, you can
+ re-assign the modified object to the container proxy::
+
+ # create a list proxy and append a mutable object (a dictionary)
+ lproxy = manager.list()
+ lproxy.append({})
+ # now mutate the dictionary
+ d = lproxy[0]
+ d['a'] = 1
+ d['b'] = 2
+ # at this point, the changes to d are not yet synced, but by
+ # reassigning the dictionary, the proxy is notified of the change
+ lproxy[0] = d
+
Namespace objects
>>>>>>>>>>>>>>>>>
Modified: python/branches/release27-maint/Doc/library/pkgutil.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/pkgutil.rst (original)
+++ python/branches/release27-maint/Doc/library/pkgutil.rst Fri Nov 26 08:34:20 2010
@@ -3,62 +3,187 @@
============================================
.. module:: pkgutil
- :synopsis: Utilities to support extension of packages.
+ :synopsis: Utilities for the import system.
+This module provides utilities for the import system, in particular package
+support.
.. versionadded:: 2.3
-This module provides functions to manipulate packages:
-
.. function:: extend_path(path, name)
- Extend the search path for the modules which comprise a package. Intended use is
- to place the following code in a package's :file:`__init__.py`::
+ Extend the search path for the modules which comprise a package. Intended
+ use is to place the following code in a package's :file:`__init__.py`::
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)
- This will add to the package's ``__path__`` all subdirectories of directories on
- ``sys.path`` named after the package. This is useful if one wants to distribute
- different parts of a single logical package as multiple directories.
-
- It also looks for :file:`\*.pkg` files beginning where ``*`` matches the *name*
- argument. This feature is similar to :file:`\*.pth` files (see the :mod:`site`
- module for more information), except that it doesn't special-case lines starting
- with ``import``. A :file:`\*.pkg` file is trusted at face value: apart from
- checking for duplicates, all entries found in a :file:`\*.pkg` file are added to
- the path, regardless of whether they exist on the filesystem. (This is a
- feature.)
+ This will add to the package's ``__path__`` all subdirectories of directories
+ on ``sys.path`` named after the package. This is useful if one wants to
+ distribute different parts of a single logical package as multiple
+ directories.
+
+ It also looks for :file:`\*.pkg` files beginning where ``*`` matches the
+ *name* argument. This feature is similar to :file:`\*.pth` files (see the
+ :mod:`site` module for more information), except that it doesn't special-case
+ lines starting with ``import``. A :file:`\*.pkg` file is trusted at face
+ value: apart from checking for duplicates, all entries found in a
+ :file:`\*.pkg` file are added to the path, regardless of whether they exist
+ on the filesystem. (This is a feature.)
If the input path is not a list (as is the case for frozen packages) it is
returned unchanged. The input path is not modified; an extended copy is
returned. Items are only appended to the copy at the end.
- It is assumed that ``sys.path`` is a sequence. Items of ``sys.path`` that are
- not (Unicode or 8-bit) strings referring to existing directories are ignored.
- Unicode items on ``sys.path`` that cause errors when used as filenames may cause
- this function to raise an exception (in line with :func:`os.path.isdir`
- behavior).
+ It is assumed that :data:`sys.path` is a sequence. Items of :data:`sys.path`
+ that are not (Unicode or 8-bit) strings referring to existing directories are
+ ignored. Unicode items on :data:`sys.path` that cause errors when used as
+ filenames may cause this function to raise an exception (in line with
+ :func:`os.path.isdir` behavior).
+
+
+.. class:: ImpImporter(dirname=None)
+
+ :pep:`302` Importer that wraps Python's "classic" import algorithm.
+
+ If *dirname* is a string, a :pep:`302` importer is created that searches that
+ directory. If *dirname* is ``None``, a :pep:`302` importer is created that
+ searches the current :data:`sys.path`, plus any modules that are frozen or
+ built-in.
+
+ Note that :class:`ImpImporter` does not currently support being used by
+ placement on :data:`sys.meta_path`.
+
+
+.. class:: ImpLoader(fullname, file, filename, etc)
+
+ :pep:`302` Loader that wraps Python's "classic" import algorithm.
+
+
+.. function:: find_loader(fullname)
+
+ Find a :pep:`302` "loader" object for *fullname*.
+
+ If *fullname* contains dots, path must be the containing package's
+ ``__path__``. Returns ``None`` if the module cannot be found or imported.
+ This function uses :func:`iter_importers`, and is thus subject to the same
+ limitations regarding platform-specific special import locations such as the
+ Windows registry.
+
+
+.. function:: get_importer(path_item)
+
+ Retrieve a :pep:`302` importer for the given *path_item*.
+
+ The returned importer is cached in :data:`sys.path_importer_cache` if it was
+ newly created by a path hook.
+
+ If there is no importer, a wrapper around the basic import machinery is
+ returned. This wrapper is never inserted into the importer cache (None is
+ inserted instead).
+
+ The cache (or part of it) can be cleared manually if a rescan of
+ :data:`sys.path_hooks` is necessary.
+
+
+.. function:: get_loader(module_or_name)
+
+ Get a :pep:`302` "loader" object for *module_or_name*.
+
+ If the module or package is accessible via the normal import mechanism, a
+ wrapper around the relevant part of that machinery is returned. Returns
+ ``None`` if the module cannot be found or imported. If the named module is
+ not already imported, its containing package (if any) is imported, in order
+ to establish the package ``__path__``.
+
+ This function uses :func:`iter_importers`, and is thus subject to the same
+ limitations regarding platform-specific special import locations such as the
+ Windows registry.
+
+
+.. function:: iter_importers(fullname='')
+
+ Yield :pep:`302` importers for the given module name.
+
+ If fullname contains a '.', the importers will be for the package containing
+ fullname, otherwise they will be importers for :data:`sys.meta_path`,
+ :data:`sys.path`, and Python's "classic" import machinery, in that order. If
+ the named module is in a package, that package is imported as a side effect
+ of invoking this function.
+
+ Non-:pep:`302` mechanisms (e.g. the Windows registry) used by the standard
+ import machinery to find files in alternative locations are partially
+ supported, but are searched *after* :data:`sys.path`. Normally, these
+ locations are searched *before* :data:`sys.path`, preventing :data:`sys.path`
+ entries from shadowing them.
+
+ For this to cause a visible difference in behaviour, there must be a module
+ or package name that is accessible via both :data:`sys.path` and one of the
+ non-:pep:`302` file system mechanisms. In this case, the emulation will find
+ the former version, while the builtin import mechanism will find the latter.
+
+ Items of the following types can be affected by this discrepancy:
+ ``imp.C_EXTENSION``, ``imp.PY_SOURCE``, ``imp.PY_COMPILED``,
+ ``imp.PKG_DIRECTORY``.
+
+
+.. function:: iter_modules(path=None, prefix='')
+
+ Yields ``(module_loader, name, ispkg)`` for all submodules on *path*, or, if
+ path is ``None``, all top-level modules on ``sys.path``.
+
+ *path* should be either ``None`` or a list of paths to look for modules in.
+
+ *prefix* is a string to output on the front of every module name on output.
+
+
+.. function:: walk_packages(path=None, prefix='', onerror=None)
+
+ Yields ``(module_loader, name, ispkg)`` for all modules recursively on
+ *path*, or, if path is ``None``, all accessible modules.
+
+ *path* should be either ``None`` or a list of paths to look for modules in.
+
+ *prefix* is a string to output on the front of every module name on output.
+
+ Note that this function must import all *packages* (*not* all modules!) on
+ the given *path*, in order to access the ``__path__`` attribute to find
+ submodules.
+
+ *onerror* is a function which gets called with one argument (the name of the
+ package which was being imported) if any exception occurs while trying to
+ import a package. If no *onerror* function is supplied, :exc:`ImportError`\s
+ are caught and ignored, while all other exceptions are propagated,
+ terminating the search.
+
+ Examples::
+
+ # list all modules python can access
+ walk_packages()
+
+ # list all submodules of ctypes
+ walk_packages(ctypes.__path__, ctypes.__name__ + '.')
+
.. function:: get_data(package, resource)
Get a resource from a package.
- This is a wrapper for the :pep:`302` loader :func:`get_data` API. The package
- argument should be the name of a package, in standard module format
- (foo.bar). The resource argument should be in the form of a relative
- filename, using ``/`` as the path separator. The parent directory name
+ This is a wrapper for the :pep:`302` loader :func:`get_data` API. The
+ *package* argument should be the name of a package, in standard module format
+ (``foo.bar``). The *resource* argument should be in the form of a relative
+ filename, using ``/`` as the path separator. The parent directory name
``..`` is not allowed, and nor is a rooted name (starting with a ``/``).
- The function returns a binary string that is the contents of the
- specified resource.
+ The function returns a binary string that is the contents of the specified
+ resource.
For packages located in the filesystem, which have already been imported,
this is the rough equivalent of::
- d = os.path.dirname(sys.modules[package].__file__)
- data = open(os.path.join(d, resource), 'rb').read()
+ d = os.path.dirname(sys.modules[package].__file__)
+ data = open(os.path.join(d, resource), 'rb').read()
If the package cannot be located or loaded, or it uses a :pep:`302` loader
- which does not support :func:`get_data`, then None is returned.
+ which does not support :func:`get_data`, then ``None`` is returned.
Modified: python/branches/release27-maint/Doc/library/sys.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/sys.rst (original)
+++ python/branches/release27-maint/Doc/library/sys.rst Fri Nov 26 08:34:20 2010
@@ -874,8 +874,9 @@
``'return'``
A function (or other code block) is about to return. The local trace
- function is called; *arg* is the value that will be returned. The trace
- function's return value is ignored.
+ function is called; *arg* is the value that will be returned, or ``None``
+ if the event is caused by an exception being raised. The trace function's
+ return value is ignored.
``'exception'``
An exception has occurred. The local trace function is called; *arg* is a
@@ -887,10 +888,10 @@
a built-in. *arg* is the C function object.
``'c_return'``
- A C function has returned. *arg* is ``None``.
+ A C function has returned. *arg* is the C function object.
``'c_exception'``
- A C function has raised an exception. *arg* is ``None``.
+ A C function has raised an exception. *arg* is the C function object.
Note that as an exception is propagated down the chain of callers, an
``'exception'`` event is generated at each level.
Modified: python/branches/release27-maint/Doc/library/time.rst
==============================================================================
--- python/branches/release27-maint/Doc/library/time.rst (original)
+++ python/branches/release27-maint/Doc/library/time.rst Fri Nov 26 08:34:20 2010
@@ -17,21 +17,23 @@
An explanation of some terminology and conventions is in order.
- .. index:: single: epoch
+.. index:: single: epoch
* The :dfn:`epoch` is the point where the time starts. On January 1st of that
year, at 0 hours, the "time since the epoch" is zero. For Unix, the epoch is
1970. To find out what the epoch is, look at ``gmtime(0)``.
- .. index:: single: Year 2038
+.. index:: single: Year 2038
* The functions in this module do not handle dates and times before the epoch or
far in the future. The cut-off point in the future is determined by the C
library; for Unix, it is typically in 2038.
- .. index::
- single: Year 2000
- single: Y2K
+.. index::
+ single: Year 2000
+ single: Y2K
+
+.. _time-y2kissues:
* **Year 2000 (Y2K) issues**: Python depends on the platform's C library, which
generally doesn't have year 2000 issues, since all dates and times are
@@ -48,16 +50,16 @@
Note that this is new as of Python 1.5.2(a2); earlier versions, up to Python
1.5.1 and 1.5.2a1, would add 1900 to year values below 1900.
- .. index::
- single: UTC
- single: Coordinated Universal Time
- single: Greenwich Mean Time
+.. index::
+ single: UTC
+ single: Coordinated Universal Time
+ single: Greenwich Mean Time
* UTC is Coordinated Universal Time (formerly known as Greenwich Mean Time, or
GMT). The acronym UTC is not a mistake but a compromise between English and
French.
- .. index:: single: Daylight Saving Time
+.. index:: single: Daylight Saving Time
* DST is Daylight Saving Time, an adjustment of the timezone by (usually) one
hour during part of the year. DST rules are magic (determined by local law) and
@@ -82,38 +84,7 @@
values of :func:`gmtime`, :func:`localtime`, and :func:`strptime` also offer
attribute names for individual fields.
- +-------+-------------------+---------------------------------+
- | Index | Attribute | Values |
- +=======+===================+=================================+
- | 0 | :attr:`tm_year` | (for example, 1993) |
- +-------+-------------------+---------------------------------+
- | 1 | :attr:`tm_mon` | range [1, 12] |
- +-------+-------------------+---------------------------------+
- | 2 | :attr:`tm_mday` | range [1, 31] |
- +-------+-------------------+---------------------------------+
- | 3 | :attr:`tm_hour` | range [0, 23] |
- +-------+-------------------+---------------------------------+
- | 4 | :attr:`tm_min` | range [0, 59] |
- +-------+-------------------+---------------------------------+
- | 5 | :attr:`tm_sec` | range [0, 61]; see **(1)** in |
- | | | :func:`strftime` description |
- +-------+-------------------+---------------------------------+
- | 6 | :attr:`tm_wday` | range [0, 6], Monday is 0 |
- +-------+-------------------+---------------------------------+
- | 7 | :attr:`tm_yday` | range [1, 366] |
- +-------+-------------------+---------------------------------+
- | 8 | :attr:`tm_isdst` | 0, 1 or -1; see below |
- +-------+-------------------+---------------------------------+
-
- Note that unlike the C structure, the month value is a range of [1, 12],
- not [0, 11].
- A year value will be handled as described under "Year 2000 (Y2K) issues" above.
- A ``-1`` argument as the daylight savings flag, passed to :func:`mktime` will
- usually result in the correct daylight savings state to be filled in.
-
- When a tuple with an incorrect length is passed to a function expecting a
- :class:`struct_time`, or having elements of the wrong type, a :exc:`TypeError`
- is raised.
+ See :class:`struct_time` for a description of these objects.
.. versionchanged:: 2.2
The time value sequence was changed from a tuple to a :class:`struct_time`, with
@@ -419,13 +390,48 @@
documented as supported.
-.. data:: struct_time
+.. class:: struct_time
The type of the time value sequence returned by :func:`gmtime`,
- :func:`localtime`, and :func:`strptime`.
+ :func:`localtime`, and :func:`strptime`. It is an object with a :term:`named
+ tuple` interface: values can be accessed by index and by attribute name. The
+ following values are present:
+
+ +-------+-------------------+---------------------------------+
+ | Index | Attribute | Values |
+ +=======+===================+=================================+
+ | 0 | :attr:`tm_year` | (for example, 1993) |
+ +-------+-------------------+---------------------------------+
+ | 1 | :attr:`tm_mon` | range [1, 12] |
+ +-------+-------------------+---------------------------------+
+ | 2 | :attr:`tm_mday` | range [1, 31] |
+ +-------+-------------------+---------------------------------+
+ | 3 | :attr:`tm_hour` | range [0, 23] |
+ +-------+-------------------+---------------------------------+
+ | 4 | :attr:`tm_min` | range [0, 59] |
+ +-------+-------------------+---------------------------------+
+ | 5 | :attr:`tm_sec` | range [0, 61]; see **(1)** in |
+ | | | :func:`strftime` description |
+ +-------+-------------------+---------------------------------+
+ | 6 | :attr:`tm_wday` | range [0, 6], Monday is 0 |
+ +-------+-------------------+---------------------------------+
+ | 7 | :attr:`tm_yday` | range [1, 366] |
+ +-------+-------------------+---------------------------------+
+ | 8 | :attr:`tm_isdst` | 0, 1 or -1; see below |
+ +-------+-------------------+---------------------------------+
.. versionadded:: 2.2
+ Note that unlike the C structure, the month value is a range of [1, 12], not
+ [0, 11]. A year value will be handled as described under :ref:`Year 2000
+ (Y2K) issues <time-y2kissues>` above. A ``-1`` argument as the daylight
+ savings flag, passed to :func:`mktime` will usually result in the correct
+ daylight savings state to be filled in.
+
+ When a tuple with an incorrect length is passed to a function expecting a
+ :class:`struct_time`, or having elements of the wrong type, a
+ :exc:`TypeError` is raised.
+
.. function:: time()
Modified: python/branches/release27-maint/Doc/tutorial/controlflow.rst
==============================================================================
--- python/branches/release27-maint/Doc/tutorial/controlflow.rst (original)
+++ python/branches/release27-maint/Doc/tutorial/controlflow.rst Fri Nov 26 08:34:20 2010
@@ -429,7 +429,8 @@
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, "?"
print "-- I'm sorry, we're all out of", kind
- for arg in arguments: print arg
+ for arg in arguments:
+ print arg
print "-" * 40
keys = sorted(keywords.keys())
for kw in keys:
1
0