summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
Diffstat (limited to 'Lib')
-rw-r--r--Lib/SimpleXMLRPCServer.py2
-rw-r--r--Lib/binhex.py9
-rw-r--r--Lib/bsddb/test/test_recno.py2
-rw-r--r--Lib/cgitb.py3
-rw-r--r--Lib/collections.py47
-rw-r--r--Lib/copy_reg.py4
-rw-r--r--Lib/distutils/dist.py2
-rw-r--r--Lib/encodings/__init__.py12
-rw-r--r--Lib/fileinput.py2
-rw-r--r--Lib/gopherlib.py209
-rw-r--r--Lib/hmac.py2
-rw-r--r--Lib/httplib.py7
-rw-r--r--Lib/idlelib/rpc.py4
-rw-r--r--Lib/imputil.py4
-rwxr-xr-xLib/lib-tk/Tix.py2
-rw-r--r--Lib/lib-tk/Tkinter.py8
-rw-r--r--Lib/optparse.py2
-rw-r--r--Lib/pickle.py2
-rw-r--r--Lib/plat-mac/macfs.py198
-rw-r--r--Lib/plat-mac/macostools.py17
-rw-r--r--Lib/posixfile.py4
-rwxr-xr-xLib/pydoc.py4
-rw-r--r--Lib/re.py2
-rw-r--r--Lib/site.py6
-rwxr-xr-xLib/symbol.py167
-rw-r--r--Lib/test/output/test_extcall15
-rwxr-xr-xLib/test/regrtest.py15
-rw-r--r--Lib/test/test___all__.py5
-rw-r--r--Lib/test/test_ast.py2
-rwxr-xr-xLib/test/test_binascii.py4
-rw-r--r--Lib/test/test_bool.py4
-rw-r--r--Lib/test/test_builtin.py13
-rw-r--r--Lib/test/test_codeop.py4
-rw-r--r--Lib/test/test_collections.py6
-rw-r--r--Lib/test/test_decorators.py36
-rw-r--r--Lib/test/test_extcall.py7
-rw-r--r--Lib/test/test_httplib.py10
-rwxr-xr-xLib/test/test_imageop.py177
-rw-r--r--Lib/test/test_macfs.py78
-rw-r--r--Lib/test/test_macostools.py6
-rw-r--r--Lib/test/test_marshal.py24
-rw-r--r--Lib/test/test_rgbimg.py70
-rw-r--r--Lib/test/test_socket.py2
-rw-r--r--Lib/test/test_sundry.py133
-rw-r--r--Lib/test/test_urllib2net.py15
-rw-r--r--Lib/test/test_xml_etree.py2
-rw-r--r--Lib/test/test_xml_etree_c.py2
-rw-r--r--Lib/test/time_hashlib.py2
-rw-r--r--Lib/timeit.py6
-rw-r--r--Lib/unittest.py6
-rw-r--r--Lib/urllib.py28
-rw-r--r--Lib/urllib2.py24
52 files changed, 341 insertions, 1076 deletions
diff --git a/Lib/SimpleXMLRPCServer.py b/Lib/SimpleXMLRPCServer.py
index 4aadffa..7056d58 100644
--- a/Lib/SimpleXMLRPCServer.py
+++ b/Lib/SimpleXMLRPCServer.py
@@ -139,7 +139,7 @@ def list_public_methods(obj):
return [member for member in dir(obj)
if not member.startswith('_') and
- callable(getattr(obj, member))]
+ hasattr(getattr(obj, member), '__call__')]
def remove_duplicates(lst):
"""remove_duplicates([2,2,2,1,3,3]) => [3,1,2]
diff --git a/Lib/binhex.py b/Lib/binhex.py
index 69ac097..bd4e8b3 100644
--- a/Lib/binhex.py
+++ b/Lib/binhex.py
@@ -511,14 +511,7 @@ def hexbin(inp, out):
ifp.close()
def _test():
- if os.name == 'mac':
- import macfs
- fss, ok = macfs.PromptGetFile('File to convert:')
- if not ok:
- sys.exit(0)
- fname = fss.as_pathname()
- else:
- fname = sys.argv[1]
+ fname = sys.argv[1]
binhex(fname, fname+'.hqx')
hexbin(fname+'.hqx', fname+'.viahqx')
#hexbin(fname, fname+'.unpacked')
diff --git a/Lib/bsddb/test/test_recno.py b/Lib/bsddb/test/test_recno.py
index fb361b0..a05f23c 100644
--- a/Lib/bsddb/test/test_recno.py
+++ b/Lib/bsddb/test/test_recno.py
@@ -118,7 +118,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
assert not d.has_key(13)
data = d.get_both(26, "z" * 60)
- assert data == "z" * 60
+ assert data == "z" * 60, 'was %r' % data
if verbose:
print(data)
diff --git a/Lib/cgitb.py b/Lib/cgitb.py
index 3f36ab1..e5db383 100644
--- a/Lib/cgitb.py
+++ b/Lib/cgitb.py
@@ -183,7 +183,8 @@ function calls leading up to the error, in the order they occurred.</p>'''
%s
-->
-''' % ''.join(traceback.format_exception(etype, evalue, etb))
+''' % pydoc.html.escape(
+ ''.join(traceback.format_exception(etype, evalue, etb)))
def text(einfo, context=5):
"""Return a plain text document describing a given traceback."""
diff --git a/Lib/collections.py b/Lib/collections.py
index dba9c7d..2cf9fe8 100644
--- a/Lib/collections.py
+++ b/Lib/collections.py
@@ -24,30 +24,29 @@ def NamedTuple(typename, s):
"""
field_names = s.split()
- nargs = len(field_names)
-
- def __new__(cls, *args, **kwds):
- if kwds:
- try:
- args += tuple(kwds[name] for name in field_names[len(args):])
- except KeyError as name:
- raise TypeError('%s missing required argument: %s' % (typename, name))
- if len(args) != nargs:
- raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, nargs, len(args)))
- return tuple.__new__(cls, args)
-
- repr_template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name in field_names))
-
- m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup)
- m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)),
- __slots__ = (), # no per-instance dict (so instances are same size as tuples)
- __new__ = __new__,
- __repr__ = lambda self, _format=repr_template.__mod__: _format(self),
- __module__ = _sys._getframe(1).f_globals['__name__'],
- )
- m.update((name, property(_itemgetter(index))) for index, name in enumerate(field_names))
-
- return type(typename, (tuple,), m)
+ if not ''.join([typename] + field_names).replace('_', '').isalnum():
+ raise ValueError('Type names and field names can only contain alphanumeric characters and underscores')
+ argtxt = ', '.join(field_names)
+ reprtxt = ', '.join('%s=%%r' % name for name in field_names)
+ template = '''class %(typename)s(tuple):
+ '%(typename)s(%(argtxt)s)'
+ __slots__ = ()
+ def __new__(cls, %(argtxt)s):
+ return tuple.__new__(cls, (%(argtxt)s,))
+ def __repr__(self):
+ return '%(typename)s(%(reprtxt)s)' %% self
+ ''' % locals()
+ for i, name in enumerate(field_names):
+ template += '\n %s = property(itemgetter(%d))\n' % (name, i)
+ m = dict(itemgetter=_itemgetter)
+ exec(template, m)
+ result = m[typename]
+ if hasattr(_sys, '_getframe'):
+ result.__module__ = _sys._getframe(1).f_globals['__name__']
+ return result
+
+
+
if __name__ == '__main__':
diff --git a/Lib/copy_reg.py b/Lib/copy_reg.py
index 58d462b..4f77c6f 100644
--- a/Lib/copy_reg.py
+++ b/Lib/copy_reg.py
@@ -10,7 +10,7 @@ __all__ = ["pickle", "constructor",
dispatch_table = {}
def pickle(ob_type, pickle_function, constructor_ob=None):
- if not callable(pickle_function):
+ if not hasattr(pickle_function, '__call__'):
raise TypeError("reduction functions must be callable")
dispatch_table[ob_type] = pickle_function
@@ -20,7 +20,7 @@ def pickle(ob_type, pickle_function, constructor_ob=None):
constructor(constructor_ob)
def constructor(object):
- if not callable(object):
+ if not hasattr(object, '__call__'):
raise TypeError("constructors must be callable")
# Example: provide pickling support for complex numbers.
diff --git a/Lib/distutils/dist.py b/Lib/distutils/dist.py
index 89390fb..e89d942 100644
--- a/Lib/distutils/dist.py
+++ b/Lib/distutils/dist.py
@@ -569,7 +569,7 @@ Common commands: (see '--help-commands' for more)
#print "showing help for option %s of command %s" % \
# (help_option[0],cmd_class)
- if callable(func):
+ if hasattr(func, '__call__'):
func()
else:
raise DistutilsClassError(
diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py
index 5bfee44..90ff479 100644
--- a/Lib/encodings/__init__.py
+++ b/Lib/encodings/__init__.py
@@ -122,12 +122,12 @@ def search_function(encoding):
raise CodecRegistryError,\
'module "%s" (%s) failed to register' % \
(mod.__name__, mod.__file__)
- if not callable(entry[0]) or \
- not callable(entry[1]) or \
- (entry[2] is not None and not callable(entry[2])) or \
- (entry[3] is not None and not callable(entry[3])) or \
- (len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \
- (len(entry) > 5 and entry[5] is not None and not callable(entry[5])):
+ if not hasattr(entry[0], '__call__') or \
+ not hasattr(entry[1], '__call__') or \
+ (entry[2] is not None and not hasattr(entry[2], '__call__')) or \
+ (entry[3] is not None and not hasattr(entry[3], '__call__')) or \
+ (len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \
+ (len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')):
raise CodecRegistryError,\
'incompatible codecs in module "%s" (%s)' % \
(mod.__name__, mod.__file__)
diff --git a/Lib/fileinput.py b/Lib/fileinput.py
index b8b9870..53e7c09 100644
--- a/Lib/fileinput.py
+++ b/Lib/fileinput.py
@@ -226,7 +226,7 @@ class FileInput:
self._mode = mode
if inplace and openhook:
raise ValueError("FileInput cannot use an opening hook in inplace mode")
- elif openhook and not callable(openhook):
+ elif openhook and not hasattr(openhook, '__call__'):
raise ValueError("FileInput openhook must be callable")
self._openhook = openhook
diff --git a/Lib/gopherlib.py b/Lib/gopherlib.py
deleted file mode 100644
index 2fad21c..0000000
--- a/Lib/gopherlib.py
+++ /dev/null
@@ -1,209 +0,0 @@
-"""Gopher protocol client interface."""
-
-__all__ = ["send_selector","send_query"]
-
-import warnings
-warnings.warn("the gopherlib module is deprecated", DeprecationWarning,
- stacklevel=2)
-
-# Default selector, host and port
-DEF_SELECTOR = '1/'
-DEF_HOST = 'gopher.micro.umn.edu'
-DEF_PORT = 70
-
-# Recognized file types
-A_TEXT = '0'
-A_MENU = '1'
-A_CSO = '2'
-A_ERROR = '3'
-A_MACBINHEX = '4'
-A_PCBINHEX = '5'
-A_UUENCODED = '6'
-A_INDEX = '7'
-A_TELNET = '8'
-A_BINARY = '9'
-A_DUPLICATE = '+'
-A_SOUND = 's'
-A_EVENT = 'e'
-A_CALENDAR = 'c'
-A_HTML = 'h'
-A_TN3270 = 'T'
-A_MIME = 'M'
-A_IMAGE = 'I'
-A_WHOIS = 'w'
-A_QUERY = 'q'
-A_GIF = 'g'
-A_HTML = 'h' # HTML file
-A_WWW = 'w' # WWW address
-A_PLUS_IMAGE = ':'
-A_PLUS_MOVIE = ';'
-A_PLUS_SOUND = '<'
-
-
-_names = dir()
-_type_to_name_map = {}
-def type_to_name(gtype):
- """Map all file types to strings; unknown types become TYPE='x'."""
- global _type_to_name_map
- if _type_to_name_map=={}:
- for name in _names:
- if name[:2] == 'A_':
- _type_to_name_map[eval(name)] = name[2:]
- if gtype in _type_to_name_map:
- return _type_to_name_map[gtype]
- return 'TYPE=%r' % (gtype,)
-
-# Names for characters and strings
-CRLF = '\r\n'
-TAB = '\t'
-
-def send_selector(selector, host, port = 0):
- """Send a selector to a given host and port, return a file with the reply."""
- import socket
- if not port:
- i = host.find(':')
- if i >= 0:
- host, port = host[:i], int(host[i+1:])
- if not port:
- port = DEF_PORT
- elif type(port) == type(''):
- port = int(port)
- s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- s.connect((host, port))
- s.sendall(selector + CRLF)
- s.shutdown(1)
- return s.makefile('rb')
-
-def send_query(selector, query, host, port = 0):
- """Send a selector and a query string."""
- return send_selector(selector + '\t' + query, host, port)
-
-def path_to_selector(path):
- """Takes a path as returned by urlparse and returns the appropriate selector."""
- if path=="/":
- return "/"
- else:
- return path[2:] # Cuts initial slash and data type identifier
-
-def path_to_datatype_name(path):
- """Takes a path as returned by urlparse and maps it to a string.
- See section 3.4 of RFC 1738 for details."""
- if path=="/":
- # No way to tell, although "INDEX" is likely
- return "TYPE='unknown'"
- else:
- return type_to_name(path[1])
-
-# The following functions interpret the data returned by the gopher
-# server according to the expected type, e.g. textfile or directory
-
-def get_directory(f):
- """Get a directory in the form of a list of entries."""
- entries = []
- while 1:
- line = f.readline()
- if not line:
- print('(Unexpected EOF from server)')
- break
- if line[-2:] == CRLF:
- line = line[:-2]
- elif line[-1:] in CRLF:
- line = line[:-1]
- if line == '.':
- break
- if not line:
- print('(Empty line from server)')
- continue
- gtype = line[0]
- parts = line[1:].split(TAB)
- if len(parts) < 4:
- print('(Bad line from server: %r)' % (line,))
- continue
- if len(parts) > 4:
- if parts[4:] != ['+']:
- print('(Extra info from server:', end=' ')
- print(parts[4:], ')')
- else:
- parts.append('')
- parts.insert(0, gtype)
- entries.append(parts)
- return entries
-
-def get_textfile(f):
- """Get a text file as a list of lines, with trailing CRLF stripped."""
- lines = []
- get_alt_textfile(f, lines.append)
- return lines
-
-def get_alt_textfile(f, func):
- """Get a text file and pass each line to a function, with trailing CRLF stripped."""
- while 1:
- line = f.readline()
- if not line:
- print('(Unexpected EOF from server)')
- break
- if line[-2:] == CRLF:
- line = line[:-2]
- elif line[-1:] in CRLF:
- line = line[:-1]
- if line == '.':
- break
- if line[:2] == '..':
- line = line[1:]
- func(line)
-
-def get_binary(f):
- """Get a binary file as one solid data block."""
- data = f.read()
- return data
-
-def get_alt_binary(f, func, blocksize):
- """Get a binary file and pass each block to a function."""
- while 1:
- data = f.read(blocksize)
- if not data:
- break
- func(data)
-
-def test():
- """Trivial test program."""
- import sys
- import getopt
- opts, args = getopt.getopt(sys.argv[1:], '')
- selector = DEF_SELECTOR
- type = selector[0]
- host = DEF_HOST
- if args:
- host = args[0]
- args = args[1:]
- if args:
- type = args[0]
- args = args[1:]
- if len(type) > 1:
- type, selector = type[0], type
- else:
- selector = ''
- if args:
- selector = args[0]
- args = args[1:]
- query = ''
- if args:
- query = args[0]
- args = args[1:]
- if type == A_INDEX:
- f = send_query(selector, query, host)
- else:
- f = send_selector(selector, host)
- if type == A_TEXT:
- lines = get_textfile(f)
- for item in lines: print(item)
- elif type in (A_MENU, A_INDEX):
- entries = get_directory(f)
- for item in entries: print(item)
- else:
- data = get_binary(f)
- print('binary data:', len(data), 'bytes:', repr(data[:100])[:40])
-
-# Run the test when run as script
-if __name__ == '__main__':
- test()
diff --git a/Lib/hmac.py b/Lib/hmac.py
index 52af590..079b58c 100644
--- a/Lib/hmac.py
+++ b/Lib/hmac.py
@@ -39,7 +39,7 @@ class HMAC:
import hashlib
digestmod = hashlib.md5
- if callable(digestmod):
+ if hasattr(digestmod, '__call__'):
self.digest_cons = digestmod
else:
self.digest_cons = lambda d='': digestmod.new(d)
diff --git a/Lib/httplib.py b/Lib/httplib.py
index 4c23983..2a74e54 100644
--- a/Lib/httplib.py
+++ b/Lib/httplib.py
@@ -1123,16 +1123,15 @@ class HTTPSConnection(HTTPConnection):
default_port = HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
- strict=None):
- HTTPConnection.__init__(self, host, port, strict)
+ strict=None, timeout=None):
+ HTTPConnection.__init__(self, host, port, strict, timeout)
self.key_file = key_file
self.cert_file = cert_file
def connect(self):
"Connect to a host on a given (SSL) port."
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- sock.connect((self.host, self.port))
+ sock = socket.create_connection((self.host, self.port), self.timeout)
ssl = socket.ssl(sock, self.key_file, self.cert_file)
self.sock = FakeSocket(sock, ssl)
diff --git a/Lib/idlelib/rpc.py b/Lib/idlelib/rpc.py
index 57a975a..e041211 100644
--- a/Lib/idlelib/rpc.py
+++ b/Lib/idlelib/rpc.py
@@ -572,7 +572,7 @@ def _getmethods(obj, methods):
# Adds names to dictionary argument 'methods'
for name in dir(obj):
attr = getattr(obj, name)
- if callable(attr):
+ if hasattr(attr, '__call__'):
methods[name] = 1
if type(obj) == types.ClassType:
for super in obj.__bases__:
@@ -581,7 +581,7 @@ def _getmethods(obj, methods):
def _getattributes(obj, attributes):
for name in dir(obj):
attr = getattr(obj, name)
- if not callable(attr):
+ if not hasattr(attr, '__call__'):
attributes[name] = 1
class MethodProxy(object):
diff --git a/Lib/imputil.py b/Lib/imputil.py
index 213799f..dbf0922 100644
--- a/Lib/imputil.py
+++ b/Lib/imputil.py
@@ -48,7 +48,7 @@ class ImportManager:
self.namespace['__import__'] = self.previous_importer
def add_suffix(self, suffix, importFunc):
- assert callable(importFunc)
+ assert hasattr(importFunc, '__call__')
self.fs_imp.add_suffix(suffix, importFunc)
######################################################################
@@ -539,7 +539,7 @@ class _FilesystemImporter(Importer):
self.suffixes = [ ]
def add_suffix(self, suffix, importFunc):
- assert callable(importFunc)
+ assert hasattr(importFunc, '__call__')
self.suffixes.append((suffix, importFunc))
def import_from_dir(self, dir, fqname):
diff --git a/Lib/lib-tk/Tix.py b/Lib/lib-tk/Tix.py
index ad6126a..970e7ae 100755
--- a/Lib/lib-tk/Tix.py
+++ b/Lib/lib-tk/Tix.py
@@ -390,7 +390,7 @@ class TixWidget(Tkinter.Widget):
elif kw: cnf = kw
options = ()
for k, v in cnf.items():
- if callable(v):
+ if hasattr(v, '__call__'):
v = self._register(v)
options = options + ('-'+k, v)
return master.tk.call(('image', 'create', imgtype,) + options)
diff --git a/Lib/lib-tk/Tkinter.py b/Lib/lib-tk/Tkinter.py
index 248a702..5a73ca8 100644
--- a/Lib/lib-tk/Tkinter.py
+++ b/Lib/lib-tk/Tkinter.py
@@ -1053,7 +1053,7 @@ class Misc:
for k, v in cnf.items():
if v is not None:
if k[-1] == '_': k = k[:-1]
- if callable(v):
+ if hasattr(v, '__call__'):
v = self._register(v)
res = res + ('-'+k, v)
return res
@@ -1570,7 +1570,7 @@ class Wm:
"""Bind function FUNC to command NAME for this widget.
Return the function bound to NAME if None is given. NAME could be
e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
- if callable(func):
+ if hasattr(func, '__call__'):
command = self._register(func)
else:
command = func
@@ -3221,7 +3221,7 @@ class Image:
elif kw: cnf = kw
options = ()
for k, v in cnf.items():
- if callable(v):
+ if hasattr(v, '__call__'):
v = self._register(v)
options = options + ('-'+k, v)
self.tk.call(('image', 'create', imgtype, name,) + options)
@@ -3244,7 +3244,7 @@ class Image:
for k, v in _cnfmerge(kw).items():
if v is not None:
if k[-1] == '_': k = k[:-1]
- if callable(v):
+ if hasattr(v, '__call__'):
v = self._register(v)
res = res + ('-'+k, v)
self.tk.call((self.name, 'config') + res)
diff --git a/Lib/optparse.py b/Lib/optparse.py
index ae48c7c..1fc07b5 100644
--- a/Lib/optparse.py
+++ b/Lib/optparse.py
@@ -700,7 +700,7 @@ class Option:
def _check_callback(self):
if self.action == "callback":
- if not callable(self.callback):
+ if not hasattr(self.callback, '__call__'):
raise OptionError(
"callback not callable: %r" % self.callback, self)
if (self.callback_args is not None and
diff --git a/Lib/pickle.py b/Lib/pickle.py
index c93352f..a028d9d 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -346,7 +346,7 @@ class Pickler:
raise PicklingError("args from reduce() should be a tuple")
# Assert that func is callable
- if not callable(func):
+ if not hasattr(func, '__call__'):
raise PicklingError("func from reduce should be callable")
save = self.save
diff --git a/Lib/plat-mac/macfs.py b/Lib/plat-mac/macfs.py
deleted file mode 100644
index 6ec4bef..0000000
--- a/Lib/plat-mac/macfs.py
+++ /dev/null
@@ -1,198 +0,0 @@
-"""macfs - Pure Python module designed to be backward compatible with
-macfs and MACFS.
-"""
-import sys
-import struct
-import Carbon.Res
-import Carbon.File
-import warnings
-
-warnings.warn("macfs is deprecated, use Carbon.File, Carbon.Folder or EasyDialogs",
- DeprecationWarning, stacklevel=2)
-
-# First step: ensure we also emulate the MACFS module, which contained
-# all the constants
-
-sys.modules['MACFS'] = sys.modules[__name__]
-
-# Import all those constants
-from Carbon.Files import *
-from Carbon.Folders import *
-
-# For some obscure historical reason these are here too:
-READ = 1
-WRITE = 2
-smAllScripts = -3
-
-#
-# Find the epoch conversion for file dates in a way that works on OS9 and OSX
-import time
-if time.gmtime(0)[0] == 1970:
- _EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000
- def _utc2time(utc):
- t = utc[1] + _EPOCHCONVERT
- return int(t)
- def _time2utc(t):
- t = int(t) - _EPOCHCONVERT
- if t < -0x7fffffff:
- t = t + 0x10000000
- return (0, int(t), 0)
-else:
- def _utc2time(utc):
- t = utc[1]
- if t < 0:
- t = t + 0x100000000
- return t
- def _time2utc(t):
- if t > 0x7fffffff:
- t = t - 0x100000000
- return (0, int(t), 0)
-
-# The old name of the error object:
-error = Carbon.File.Error
-
-#
-# The various objects macfs used to export. We override them here, because some
-# of the method names are subtly different.
-#
-class FSSpec(Carbon.File.FSSpec):
- def as_fsref(self):
- return FSRef(self)
-
- def NewAlias(self, src=None):
- return Alias(Carbon.File.NewAlias(src, self))
-
- def GetCreatorType(self):
- finfo = self.FSpGetFInfo()
- return finfo.Creator, finfo.Type
-
- def SetCreatorType(self, ctor, tp):
- finfo = self.FSpGetFInfo()
- finfo.Creator = ctor
- finfo.Type = tp
- self.FSpSetFInfo(finfo)
-
- def GetFInfo(self):
- return self.FSpGetFInfo()
-
- def SetFInfo(self, info):
- return self.FSpSetFInfo(info)
-
- def GetDates(self):
- catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
- catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags)
- cdate = catinfo.createDate
- mdate = catinfo.contentModDate
- bdate = catinfo.backupDate
- return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate)
-
- def SetDates(self, cdate, mdate, bdate):
- catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
- catinfo = Carbon.File.FSCatalogInfo(
- createDate = _time2utc(cdate),
- contentModDate = _time2utc(mdate),
- backupDate = _time2utc(bdate))
- FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo)
-
-class FSRef(Carbon.File.FSRef):
- def as_fsspec(self):
- return FSSpec(self)
-
-class Alias(Carbon.File.Alias):
-
- def GetInfo(self, index):
- return self.GetAliasInfo(index)
-
- def Update(self, *args):
- pass # print "Alias.Update not yet implemented"
-
- def Resolve(self, src=None):
- fss, changed = self.ResolveAlias(src)
- return FSSpec(fss), changed
-
-from Carbon.File import FInfo
-
-# Backward-compatible type names:
-FSSpecType = FSSpec
-FSRefType = FSRef
-AliasType = Alias
-FInfoType = FInfo
-
-# Global functions:
-def ResolveAliasFile(fss, chain=1):
- fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain)
- return FSSpec(fss), isdir, isalias
-
-def RawFSSpec(data):
- return FSSpec(rawdata=data)
-
-def RawAlias(data):
- return Alias(rawdata=data)
-
-def FindApplication(*args):
- raise NotImplementedError, "FindApplication no longer implemented"
-
-def NewAliasMinimalFromFullPath(path):
- return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', ''))
-
-# Another global function:
-from Carbon.Folder import FindFolder
-
-#
-# Finally the old Standard File routine emulators.
-#
-
-_curfolder = None
-
-def StandardGetFile(*typelist):
- """Ask for an input file, optionally specifying 4-char file types that are
- allowable"""
- return PromptGetFile('', *typelist)
-
-def PromptGetFile(prompt, *typelist):
- """Ask for an input file giving the user a prompt message. Optionally you can
- specifying 4-char file types that are allowable"""
- import EasyDialogs
- warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
- DeprecationWarning, stacklevel=2)
- if not typelist:
- typelist = None
- fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
- typeList=typelist, defaultLocation=_handleSetFolder())
- return fss, not fss is None
-
-def StandardPutFile(prompt, default=None):
- """Ask the user for an output file, with a prompt. Optionally you cn supply a
- default output filename"""
- import EasyDialogs
- warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
- DeprecationWarning, stacklevel=2)
- fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
- savedFileName=default, defaultLocation=_handleSetFolder())
- return fss, not fss is None
-
-def SetFolder(folder):
- global _curfolder
- warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
- DeprecationWarning, stacklevel=2)
- if _curfolder:
- rv = FSSpec(_curfolder)
- else:
- rv = None
- _curfolder = folder
- return rv
-
-def _handleSetFolder():
- global _curfolder
- rv = _curfolder
- _curfolder = None
- return rv
-
-def GetDirectory(prompt=None):
- """Ask the user to select a folder. Optionally you can give a prompt."""
- import EasyDialogs
- warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
- DeprecationWarning, stacklevel=2)
- fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
- defaultLocation=_handleSetFolder())
- return fss, not fss is None
diff --git a/Lib/plat-mac/macostools.py b/Lib/plat-mac/macostools.py
index 2adc8aa..27d2f83 100644
--- a/Lib/plat-mac/macostools.py
+++ b/Lib/plat-mac/macostools.py
@@ -65,21 +65,9 @@ def mkdirs(dst):
def touched(dst):
"""Tell the finder a file has changed. No-op on MacOSX."""
- if sys.platform != 'mac': return
import warnings
- warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
- import macfs
- file_fss = macfs.FSSpec(dst)
- vRefNum, dirID, name = file_fss.as_tuple()
- dir_fss = macfs.FSSpec((vRefNum, dirID, ''))
- crdate, moddate, bkdate = dir_fss.GetDates()
- now = time.time()
- if now == moddate:
- now = now + 1
- try:
- dir_fss.SetDates(crdate, now, bkdate)
- except macfs.error:
- pass
+ warnings.warn("macostools.touched() has been deprecated",
+ DeprecationWarning, 2)
def touched_ae(dst):
"""Tell the finder a file has changed"""
@@ -129,7 +117,6 @@ def copy(src, dst, createpath=0, copydates=1, forcetype=None):
dstfsr = File.FSRef(dst)
catinfo, _, _, _ = srcfsr.FSGetCatalogInfo(Files.kFSCatInfoAllDates)
dstfsr.FSSetCatalogInfo(Files.kFSCatInfoAllDates, catinfo)
- touched(dstfss)
def copytree(src, dst, copydates=1):
"""Copy a complete file tree to a new destination"""
diff --git a/Lib/posixfile.py b/Lib/posixfile.py
index 763c605..2fa600f 100644
--- a/Lib/posixfile.py
+++ b/Lib/posixfile.py
@@ -52,7 +52,9 @@ f.lock(mode [, len [, start [, whence]]])
note: - the '?' modifier prevents a region from being locked; it is
query only
"""
-
+import warnings
+warnings.warn("The posixfile module is deprecated; "
+ "fcntl.lockf() provides better locking", DeprecationWarning, 2)
class _posixfile_:
"""File wrapper class that provides extra POSIX file routines."""
diff --git a/Lib/pydoc.py b/Lib/pydoc.py
index 0716a3a..78b00e7 100755
--- a/Lib/pydoc.py
+++ b/Lib/pydoc.py
@@ -754,7 +754,7 @@ class HTMLDoc(Doc):
push(msg)
for name, kind, homecls, value in ok:
base = self.docother(getattr(object, name), name, mod)
- if callable(value) or inspect.isdatadescriptor(value):
+ if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
doc = getattr(value, "__doc__", None)
else:
doc = None
@@ -1169,7 +1169,7 @@ class TextDoc(Doc):
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
- if callable(value) or inspect.isdatadescriptor(value):
+ if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
doc = getdoc(value)
else:
doc = None
diff --git a/Lib/re.py b/Lib/re.py
index 7388e4b..534ab23 100644
--- a/Lib/re.py
+++ b/Lib/re.py
@@ -306,7 +306,7 @@ class Scanner:
if i == j:
break
action = self.lexicon[m.lastindex-1][1]
- if callable(action):
+ if hasattr(action, '__call__'):
self.match = m
action = action(self, m.group())
if action is not None:
diff --git a/Lib/site.py b/Lib/site.py
index 47196e4..0871579 100644
--- a/Lib/site.py
+++ b/Lib/site.py
@@ -118,8 +118,10 @@ def _init_pathinfo():
return d
def addpackage(sitedir, name, known_paths):
- """Add a new path to known_paths by combining sitedir and 'name' or execute
- sitedir if it starts with 'import'"""
+ """Process a .pth file within the site-packages directory:
+ For each line in the file, either combine it with sitedir to a path
+ and add that to known_paths, or execute it if it starts with 'import '.
+ """
if known_paths is None:
_init_pathinfo()
reset = 1
diff --git a/Lib/symbol.py b/Lib/symbol.py
index 4ceaf2d..81624af 100755
--- a/Lib/symbol.py
+++ b/Lib/symbol.py
@@ -15,89 +15,90 @@ file_input = 257
eval_input = 258
decorator = 259
decorators = 260
-funcdef = 261
-parameters = 262
-typedargslist = 263
-tname = 264
-tfpdef = 265
-tfplist = 266
-varargslist = 267
-vname = 268
-vfpdef = 269
-vfplist = 270
-stmt = 271
-simple_stmt = 272
-small_stmt = 273
-expr_stmt = 274
-augassign = 275
-del_stmt = 276
-pass_stmt = 277
-flow_stmt = 278
-break_stmt = 279
-continue_stmt = 280
-return_stmt = 281
-yield_stmt = 282
-raise_stmt = 283
-import_stmt = 284
-import_name = 285
-import_from = 286
-import_as_name = 287
-dotted_as_name = 288
-import_as_names = 289
-dotted_as_names = 290
-dotted_name = 291
-global_stmt = 292
-nonlocal_stmt = 293
-assert_stmt = 294
-compound_stmt = 295
-if_stmt = 296
-while_stmt = 297
-for_stmt = 298
-try_stmt = 299
-with_stmt = 300
-with_var = 301
-except_clause = 302
-suite = 303
-testlist_safe = 304
-old_test = 305
-old_lambdef = 306
-test = 307
-or_test = 308
-and_test = 309
-not_test = 310
-comparison = 311
-comp_op = 312
-expr = 313
-xor_expr = 314
-and_expr = 315
-shift_expr = 316
-arith_expr = 317
-term = 318
-factor = 319
-power = 320
-atom = 321
-listmaker = 322
-testlist_gexp = 323
-lambdef = 324
-trailer = 325
-subscriptlist = 326
-subscript = 327
-sliceop = 328
-exprlist = 329
-testlist = 330
-dictsetmaker = 331
-classdef = 332
-arglist = 333
-argument = 334
-list_iter = 335
-list_for = 336
-list_if = 337
-gen_iter = 338
-gen_for = 339
-gen_if = 340
-testlist1 = 341
-encoding_decl = 342
-yield_expr = 343
+decorated_thing = 261
+funcdef = 262
+parameters = 263
+typedargslist = 264
+tname = 265
+tfpdef = 266
+tfplist = 267
+varargslist = 268
+vname = 269
+vfpdef = 270
+vfplist = 271
+stmt = 272
+simple_stmt = 273
+small_stmt = 274
+expr_stmt = 275
+augassign = 276
+del_stmt = 277
+pass_stmt = 278
+flow_stmt = 279
+break_stmt = 280
+continue_stmt = 281
+return_stmt = 282
+yield_stmt = 283
+raise_stmt = 284
+import_stmt = 285
+import_name = 286
+import_from = 287
+import_as_name = 288
+dotted_as_name = 289
+import_as_names = 290
+dotted_as_names = 291
+dotted_name = 292
+global_stmt = 293
+nonlocal_stmt = 294
+assert_stmt = 295
+compound_stmt = 296
+if_stmt = 297
+while_stmt = 298
+for_stmt = 299
+try_stmt = 300
+with_stmt = 301
+with_var = 302
+except_clause = 303
+suite = 304
+testlist_safe = 305
+old_test = 306
+old_lambdef = 307
+test = 308
+or_test = 309
+and_test = 310
+not_test = 311
+comparison = 312
+comp_op = 313
+expr = 314
+xor_expr = 315
+and_expr = 316
+shift_expr = 317
+arith_expr = 318
+term = 319
+factor = 320
+power = 321
+atom = 322
+listmaker = 323
+testlist_gexp = 324
+lambdef = 325
+trailer = 326
+subscriptlist = 327
+subscript = 328
+sliceop = 329
+exprlist = 330
+testlist = 331
+dictsetmaker = 332
+classdef = 333
+arglist = 334
+argument = 335
+list_iter = 336
+list_for = 337
+list_if = 338
+gen_iter = 339
+gen_for = 340
+gen_if = 341
+testlist1 = 342
+encoding_decl = 343
+yield_expr = 344
#--end constants--
sym_name = {}
diff --git a/Lib/test/output/test_extcall b/Lib/test/output/test_extcall
index faf0902..323fe7a 100644
--- a/Lib/test/output/test_extcall
+++ b/Lib/test/output/test_extcall
@@ -9,6 +9,9 @@ test_extcall
(1, 2, 3) {'a': 4, 'b': 5}
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
+(1, 2, 3) {'a': 4, 'b': 5}
+(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
+(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
TypeError: g() takes at least 1 positional argument (0 given)
TypeError: g() takes at least 1 positional argument (0 given)
TypeError: g() takes at least 1 positional argument (0 given)
@@ -25,12 +28,12 @@ g() got multiple values for keyword argument 'x'
g() got multiple values for keyword argument 'b'
f() keywords must be strings
h() got an unexpected keyword argument 'e'
-h() argument after * must be a sequence
-dir() argument after * must be a sequence
-NoneType object argument after * must be a sequence
-h() argument after ** must be a dictionary
-dir() argument after ** must be a dictionary
-NoneType object argument after ** must be a dictionary
+h() argument after * must be a sequence, not function
+dir() argument after * must be a sequence, not function
+NoneType object argument after * must be a sequence, not function
+h() argument after ** must be a mapping, not function
+dir() argument after ** must be a mapping, not function
+NoneType object argument after ** must be a mapping, not function
dir() got multiple values for keyword argument 'b'
3 512 True
3
diff --git a/Lib/test/regrtest.py b/Lib/test/regrtest.py
index 1cd553c..90a030d 100755
--- a/Lib/test/regrtest.py
+++ b/Lib/test/regrtest.py
@@ -1108,7 +1108,6 @@ _expectations = {
test_gdbm
test_linuxaudiodev
test_locale
- test_macfs
test_macostools
test_nis
test_ossaudiodev
@@ -1139,7 +1138,6 @@ _expectations = {
test_gdbm
test_gzip
test_linuxaudiodev
- test_macfs
test_macostools
test_nis
test_ossaudiodev
@@ -1163,7 +1161,6 @@ _expectations = {
test_gdbm
test_linuxaudiodev
test_locale
- test_macfs
test_macostools
test_nis
test_normalization
@@ -1191,7 +1188,6 @@ _expectations = {
test_gdbm
test_linuxaudiodev
test_locale
- test_macfs
test_macostools
test_nis
test_ossaudiodev
@@ -1229,12 +1225,8 @@ class _ExpectedSkips:
if test_timeout.skip_expected:
self.expected.add('test_timeout')
- if sys.maxint == 9223372036854775807:
- self.expected.add('test_rgbimg')
- self.expected.add('test_imageop')
-
if not sys.platform in ("mac", "darwin"):
- MAC_ONLY = ["test_macostools", "test_macfs", "test_aepack",
+ MAC_ONLY = ["test_macostools", "test_aepack",
"test_plistlib", "test_scriptpackages"]
for skip in MAC_ONLY:
self.expected.add(skip)
@@ -1245,6 +1237,11 @@ class _ExpectedSkips:
for skip in WIN_ONLY:
self.expected.add(skip)
+ if sys.platform != 'irix':
+ IRIX_ONLY =["test_imageop"]
+ for skip in IRIX_ONLY:
+ self.expected.add(skip)
+
self.valid = True
def isvalid(self):
diff --git a/Lib/test/test___all__.py b/Lib/test/test___all__.py
index 2c4e103..cc3780d 100644
--- a/Lib/test/test___all__.py
+++ b/Lib/test/test___all__.py
@@ -3,10 +3,6 @@ from test.test_support import verbose, run_unittest
import sys
import warnings
-warnings.filterwarnings("ignore",
- "the gopherlib module is deprecated",
- DeprecationWarning,
- "<string>")
class AllTest(unittest.TestCase):
@@ -78,7 +74,6 @@ class AllTest(unittest.TestCase):
self.check_all("getpass")
self.check_all("gettext")
self.check_all("glob")
- self.check_all("gopherlib")
self.check_all("gzip")
self.check_all("heapq")
self.check_all("htmllib")
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 308ddae..b8c1ed9 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -152,7 +152,7 @@ def run_tests():
#### EVERYTHING BELOW IS GENERATED #####
exec_results = [
('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
-('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))])]),
+('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [], )]),
('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]),
('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py
index 6a295e9..a4ee7f8 100755
--- a/Lib/test/test_binascii.py
+++ b/Lib/test/test_binascii.py
@@ -26,10 +26,10 @@ class BinASCIITest(unittest.TestCase):
prefixes.extend(["crc_", "rlecode_", "rledecode_"])
for prefix in prefixes:
name = prefix + suffix
- self.assert_(callable(getattr(binascii, name)))
+ self.assert_(hasattr(getattr(binascii, name), '__call__'))
self.assertRaises(TypeError, getattr(binascii, name))
for name in ("hexlify", "unhexlify"):
- self.assert_(callable(getattr(binascii, name)))
+ self.assert_(hasattr(getattr(binascii, name), '__call__'))
self.assertRaises(TypeError, getattr(binascii, name))
def test_base64valid(self):
diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py
index 3788f08..1fc9c05 100644
--- a/Lib/test/test_bool.py
+++ b/Lib/test/test_bool.py
@@ -168,8 +168,8 @@ class BoolTest(unittest.TestCase):
self.assertIs(hasattr([], "wobble"), False)
def test_callable(self):
- self.assertIs(callable(len), True)
- self.assertIs(callable(1), False)
+ self.assertIs(hasattr(len, '__call__'), True)
+ self.assertIs(hasattr(1, '__call__'), False)
def test_isinstance(self):
self.assertIs(isinstance(True, bool), True)
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 7f1b848..4e1375a 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -146,20 +146,21 @@ class BuiltinTest(unittest.TestCase):
self.assert_(isinstance(x, int))
self.assertEqual(-x, sys.maxint+1)
+ # XXX(nnorwitz): This test case for callable should probably be removed.
def test_callable(self):
- self.assert_(callable(len))
+ self.assert_(hasattr(len, '__call__'))
def f(): pass
- self.assert_(callable(f))
+ self.assert_(hasattr(f, '__call__'))
class C:
def meth(self): pass
- self.assert_(callable(C))
+ self.assert_(hasattr(C, '__call__'))
x = C()
- self.assert_(callable(x.meth))
- self.assert_(not callable(x))
+ self.assert_(hasattr(x.meth, '__call__'))
+ self.assert_(not hasattr(x, '__call__'))
class D(C):
def __call__(self): pass
y = D()
- self.assert_(callable(y))
+ self.assert_(hasattr(y, '__call__'))
y()
def test_chr(self):
diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py
index 38a192b..b3fd18a 100644
--- a/Lib/test/test_codeop.py
+++ b/Lib/test/test_codeop.py
@@ -13,8 +13,8 @@ if is_jython:
def unify_callables(d):
for n,v in d.items():
- if callable(v):
- d[n] = callable
+ if hasattr(v, '__call__'):
+ d[n] = True
return d
class CodeopTests(unittest.TestCase):
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index a139129..f5dad7d 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -11,7 +11,9 @@ class TestNamedTuple(unittest.TestCase):
self.assertEqual(Point.__slots__, ())
self.assertEqual(Point.__module__, __name__)
self.assertEqual(Point.__getitem__, tuple.__getitem__)
- self.assert_('__getitem__' in Point.__dict__) # superclass methods localized
+ self.assertRaises(ValueError, NamedTuple, 'abc%', 'def ghi')
+ self.assertRaises(ValueError, NamedTuple, 'abc', 'def g%hi')
+ NamedTuple('Point0', 'x1 y2') # Verify that numbers are allowed in names
def test_instance(self):
Point = NamedTuple('Point', 'x y')
@@ -50,8 +52,10 @@ class TestNamedTuple(unittest.TestCase):
def test_main(verbose=None):
+ import collections as CollectionsModule
test_classes = [TestNamedTuple]
test_support.run_unittest(*test_classes)
+ test_support.run_doctest(CollectionsModule, verbose)
if __name__ == "__main__":
test_main(verbose=True)
diff --git a/Lib/test/test_decorators.py b/Lib/test/test_decorators.py
index 2558247..1499004 100644
--- a/Lib/test/test_decorators.py
+++ b/Lib/test/test_decorators.py
@@ -266,8 +266,44 @@ class TestDecorators(unittest.TestCase):
self.assertEqual(bar(), 42)
self.assertEqual(actions, expected_actions)
+class TestClassDecorators(unittest.TestCase):
+
+ def test_simple(self):
+ def plain(x):
+ x.extra = 'Hello'
+ return x
+ @plain
+ class C(object): pass
+ self.assertEqual(C.extra, 'Hello')
+
+ def test_double(self):
+ def ten(x):
+ x.extra = 10
+ return x
+ def add_five(x):
+ x.extra += 5
+ return x
+
+ @add_five
+ @ten
+ class C(object): pass
+ self.assertEqual(C.extra, 15)
+
+ def test_order(self):
+ def applied_first(x):
+ x.extra = 'first'
+ return x
+ def applied_second(x):
+ x.extra = 'second'
+ return x
+ @applied_second
+ @applied_first
+ class C(object): pass
+ self.assertEqual(C.extra, 'second')
+
def test_main():
test_support.run_unittest(TestDecorators)
+ test_support.run_unittest(TestClassDecorators)
if __name__=="__main__":
test_main()
diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py
index 5525832..b183189 100644
--- a/Lib/test/test_extcall.py
+++ b/Lib/test/test_extcall.py
@@ -1,5 +1,6 @@
from test.test_support import verify, verbose, TestFailed, sortdict
from UserList import UserList
+from UserDict import UserDict
def e(a, b):
print(a, b)
@@ -25,6 +26,12 @@ f(1, 2, 3, **{'a':4, 'b':5})
f(1, 2, 3, *(4, 5), **{'a':6, 'b':7})
f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b':9})
+
+f(1, 2, 3, **UserDict(a=4, b=5))
+f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7))
+f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9))
+
+
# Verify clearing of SF bug #733667
try:
e(c=3)
diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py
index 035f0b9..9238eea 100644
--- a/Lib/test/test_httplib.py
+++ b/Lib/test/test_httplib.py
@@ -194,8 +194,16 @@ class TimeoutTest(TestCase):
httpConn.close()
+class HTTPSTimeoutTest(TestCase):
+# XXX Here should be tests for HTTPS, there isn't any right now!
+
+ def test_attributes(self):
+ # simple test to check it's storing it
+ h = httplib.HTTPSConnection(HOST, PORT, timeout=30)
+ self.assertEqual(h.timeout, 30)
+
def test_main(verbose=None):
- test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest)
+ test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, HTTPSTimeoutTest)
if __name__ == '__main__':
test_main()
diff --git a/Lib/test/test_imageop.py b/Lib/test/test_imageop.py
deleted file mode 100755
index d079473..0000000
--- a/Lib/test/test_imageop.py
+++ /dev/null
@@ -1,177 +0,0 @@
-#! /usr/bin/env python
-
-"""Test script for the imageop module. This has the side
- effect of partially testing the imgfile module as well.
- Roger E. Masse
-"""
-
-from test.test_support import verbose, unlink
-
-import imageop, uu, os
-
-import warnings
-warnings.filterwarnings("ignore",
- "the rgbimg module is deprecated",
- DeprecationWarning,
- ".*test_imageop")
-
-def main(use_rgbimg=1):
-
- # Create binary test files
- uu.decode(get_qualified_path('testrgb'+os.extsep+'uue'), 'test'+os.extsep+'rgb')
-
- if use_rgbimg:
- image, width, height = getrgbimage('test'+os.extsep+'rgb')
- else:
- image, width, height = getimage('test'+os.extsep+'rgb')
-
- # Return the selected part of image, which should by width by height
- # in size and consist of pixels of psize bytes.
- if verbose:
- print('crop')
- newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
-
- # Return image scaled to size newwidth by newheight. No interpolation
- # is done, scaling is done by simple-minded pixel duplication or removal.
- # Therefore, computer-generated images or dithered images will
- # not look nice after scaling.
- if verbose:
- print('scale')
- scaleimage = imageop.scale(image, 4, width, height, 1, 1)
-
- # Run a vertical low-pass filter over an image. It does so by computing
- # each destination pixel as the average of two vertically-aligned source
- # pixels. The main use of this routine is to forestall excessive flicker
- # if the image two vertically-aligned source pixels, hence the name.
- if verbose:
- print('tovideo')
- videoimage = imageop.tovideo (image, 4, width, height)
-
- # Convert an rgb image to an 8 bit rgb
- if verbose:
- print('rgb2rgb8')
- greyimage = imageop.rgb2rgb8(image, width, height)
-
- # Convert an 8 bit rgb image to a 24 bit rgb image
- if verbose:
- print('rgb82rgb')
- image = imageop.rgb82rgb(greyimage, width, height)
-
- # Convert an rgb image to an 8 bit greyscale image
- if verbose:
- print('rgb2grey')
- greyimage = imageop.rgb2grey(image, width, height)
-
- # Convert an 8 bit greyscale image to a 24 bit rgb image
- if verbose:
- print('grey2rgb')
- image = imageop.grey2rgb(greyimage, width, height)
-
- # Convert a 8-bit deep greyscale image to a 1-bit deep image by
- # thresholding all the pixels. The resulting image is tightly packed
- # and is probably only useful as an argument to mono2grey.
- if verbose:
- print('grey2mono')
- monoimage = imageop.grey2mono (greyimage, width, height, 0)
-
- # monoimage, width, height = getimage('monotest.rgb')
- # Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
- # All pixels that are zero-valued on input get value p0 on output and
- # all one-value input pixels get value p1 on output. To convert a
- # monochrome black-and-white image to greyscale pass the values 0 and
- # 255 respectively.
- if verbose:
- print('mono2grey')
- greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
-
- # Convert an 8-bit greyscale image to a 1-bit monochrome image using a
- # (simple-minded) dithering algorithm.
- if verbose:
- print('dither2mono')
- monoimage = imageop.dither2mono (greyimage, width, height)
-
- # Convert an 8-bit greyscale image to a 4-bit greyscale image without
- # dithering.
- if verbose:
- print('grey2grey4')
- grey4image = imageop.grey2grey4 (greyimage, width, height)
-
- # Convert an 8-bit greyscale image to a 2-bit greyscale image without
- # dithering.
- if verbose:
- print('grey2grey2')
- grey2image = imageop.grey2grey2 (greyimage, width, height)
-
- # Convert an 8-bit greyscale image to a 2-bit greyscale image with
- # dithering. As for dither2mono, the dithering algorithm is currently
- # very simple.
- if verbose:
- print('dither2grey2')
- grey2image = imageop.dither2grey2 (greyimage, width, height)
-
- # Convert a 4-bit greyscale image to an 8-bit greyscale image.
- if verbose:
- print('grey42grey')
- greyimage = imageop.grey42grey (grey4image, width, height)
-
- # Convert a 2-bit greyscale image to an 8-bit greyscale image.
- if verbose:
- print('grey22grey')
- image = imageop.grey22grey (grey2image, width, height)
-
- # Cleanup
- unlink('test'+os.extsep+'rgb')
-
-def getrgbimage(name):
- """return a tuple consisting of image (in 'imgfile' format but
- using rgbimg instead) width and height"""
-
- import rgbimg
-
- try:
- sizes = rgbimg.sizeofimage(name)
- except rgbimg.error:
- name = get_qualified_path(name)
- sizes = rgbimg.sizeofimage(name)
- if verbose:
- print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)))
-
- image = rgbimg.longimagedata(name)
- return (image, sizes[0], sizes[1])
-
-def getimage(name):
- """return a tuple consisting of
- image (in 'imgfile' format) width and height
- """
-
- import imgfile
-
- try:
- sizes = imgfile.getsizes(name)
- except imgfile.error:
- name = get_qualified_path(name)
- sizes = imgfile.getsizes(name)
- if verbose:
- print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes)))
-
- image = imgfile.read(name)
- return (image, sizes[0], sizes[1])
-
-def get_qualified_path(name):
- """ return a more qualified path to name"""
- import sys
- import os
- path = sys.path
- try:
- path = [os.path.dirname(__file__)] + path
- except NameError:
- pass
- for dir in path:
- fullname = os.path.join(dir, name)
- if os.path.exists(fullname):
- return fullname
- return name
-
-# rgbimg (unlike imgfile) is portable to platforms other than SGI.
-# So we prefer to use it.
-main(use_rgbimg=1)
diff --git a/Lib/test/test_macfs.py b/Lib/test/test_macfs.py
deleted file mode 100644
index e25250b..0000000
--- a/Lib/test/test_macfs.py
+++ /dev/null
@@ -1,78 +0,0 @@
-# Copyright (C) 2003 Python Software Foundation
-
-import unittest
-import warnings
-warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
-import macfs
-import os
-import sys
-import tempfile
-from test import test_support
-
-class TestMacfs(unittest.TestCase):
-
- def setUp(self):
- fp = open(test_support.TESTFN, 'w')
- fp.write('hello world\n')
- fp.close()
-
- def tearDown(self):
- try:
- os.unlink(test_support.TESTFN)
- except:
- pass
-
- def test_fsspec(self):
- fss = macfs.FSSpec(test_support.TESTFN)
- self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname())
-
- def test_fsref(self):
- fsr = macfs.FSRef(test_support.TESTFN)
- self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
-
- def test_fsref_unicode(self):
- if sys.getfilesystemencoding():
- testfn_unicode = str(test_support.TESTFN)
- fsr = macfs.FSRef(testfn_unicode)
- self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
-
- def test_coercion(self):
- fss = macfs.FSSpec(test_support.TESTFN)
- fsr = macfs.FSRef(test_support.TESTFN)
- fss2 = fsr.as_fsspec()
- fsr2 = fss.as_fsref()
- self.assertEqual(fss.as_pathname(), fss2.as_pathname())
- self.assertEqual(fsr.as_pathname(), fsr2.as_pathname())
-
- def test_dates(self):
- import time
- fss = macfs.FSSpec(test_support.TESTFN)
- now = int(time.time())
- fss.SetDates(now, now+1, now+2)
- dates = fss.GetDates()
- self.assertEqual(dates, (now, now+1, now+2))
-
- def test_ctor_type(self):
- fss = macfs.FSSpec(test_support.TESTFN)
- fss.SetCreatorType('Pyth', 'TEXT')
- filecr, filetp = fss.GetCreatorType()
- self.assertEqual((filecr, filetp), ('Pyth', 'TEXT'))
-
- def test_alias(self):
- fss = macfs.FSSpec(test_support.TESTFN)
- alias = fss.NewAlias()
- fss2, changed = alias.Resolve()
- self.assertEqual(changed, 0)
- self.assertEqual(fss.as_pathname(), fss2.as_pathname())
-
-
- def test_fss_alias(self):
- fss = macfs.FSSpec(test_support.TESTFN)
-
-
-def test_main():
- test_support.run_unittest(TestMacfs)
-
-
-if __name__ == '__main__':
- test_main()
diff --git a/Lib/test/test_macostools.py b/Lib/test/test_macostools.py
index f3292ce..40b690a 100644
--- a/Lib/test/test_macostools.py
+++ b/Lib/test/test_macostools.py
@@ -51,7 +51,11 @@ class TestMacostools(unittest.TestCase):
def test_touched(self):
# This really only tests that nothing unforeseen happens.
- macostools.touched(test_support.TESTFN)
+ import warnings
+ with test_support.guard_warnings_filter():
+ warnings.filterwarnings('ignore', 'macostools.touched*',
+ DeprecationWarning)
+ macostools.touched(test_support.TESTFN)
def test_copy(self):
try:
diff --git a/Lib/test/test_marshal.py b/Lib/test/test_marshal.py
index 2af6ae7..70b192d 100644
--- a/Lib/test/test_marshal.py
+++ b/Lib/test/test_marshal.py
@@ -220,6 +220,30 @@ class BugsTestCase(unittest.TestCase):
except Exception:
pass
+ def test_loads_recursion(self):
+ s = 'c' + ('X' * 4*4) + '{' * 2**20
+ self.assertRaises(ValueError, marshal.loads, s)
+
+ def test_recursion_limit(self):
+ # Create a deeply nested structure.
+ head = last = []
+ # The max stack depth should match the value in Python/marshal.c.
+ MAX_MARSHAL_STACK_DEPTH = 2000
+ for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
+ last.append([0])
+ last = last[-1]
+
+ # Verify we don't blow out the stack with dumps/load.
+ data = marshal.dumps(head)
+ new_head = marshal.loads(data)
+ # Don't use == to compare objects, it can exceed the recursion limit.
+ self.assertEqual(len(new_head), len(head))
+ self.assertEqual(len(new_head[0]), len(head[0]))
+ self.assertEqual(len(new_head[-1]), len(head[-1]))
+
+ last.append([0])
+ self.assertRaises(ValueError, marshal.dumps, head)
+
def test_main():
test_support.run_unittest(IntTestCase,
FloatTestCase,
diff --git a/Lib/test/test_rgbimg.py b/Lib/test/test_rgbimg.py
deleted file mode 100644
index 65a0f42..0000000
--- a/Lib/test/test_rgbimg.py
+++ /dev/null
@@ -1,70 +0,0 @@
-# Testing rgbimg module
-
-import warnings
-warnings.filterwarnings("ignore",
- "the rgbimg module is deprecated",
- DeprecationWarning,
- ".*test_rgbimg$")
-import rgbimg
-
-import os, uu
-
-from test.test_support import verbose, unlink, findfile
-
-class error(Exception):
- pass
-
-print('RGBimg test suite:')
-
-def testimg(rgb_file, raw_file):
- rgb_file = findfile(rgb_file)
- raw_file = findfile(raw_file)
- width, height = rgbimg.sizeofimage(rgb_file)
- rgb = rgbimg.longimagedata(rgb_file)
- if len(rgb) != width * height * 4:
- raise error, 'bad image length'
- raw = open(raw_file, 'rb').read()
- if rgb != raw:
- raise error, \
- 'images don\'t match for '+rgb_file+' and '+raw_file
- for depth in [1, 3, 4]:
- rgbimg.longstoimage(rgb, width, height, depth, '@.rgb')
- os.unlink('@.rgb')
-
-table = [
- ('testrgb'+os.extsep+'uue', 'test'+os.extsep+'rgb'),
- ('testimg'+os.extsep+'uue', 'test'+os.extsep+'rawimg'),
- ('testimgr'+os.extsep+'uue', 'test'+os.extsep+'rawimg'+os.extsep+'rev'),
- ]
-for source, target in table:
- source = findfile(source)
- target = findfile(target)
- if verbose:
- print("uudecoding", source, "->", target, "...")
- uu.decode(source, target)
-
-if verbose:
- print("testing...")
-
-ttob = rgbimg.ttob(0)
-if ttob != 0:
- raise error, 'ttob should start out as zero'
-
-testimg('test'+os.extsep+'rgb', 'test'+os.extsep+'rawimg')
-
-ttob = rgbimg.ttob(1)
-if ttob != 0:
- raise error, 'ttob should be zero'
-
-testimg('test'+os.extsep+'rgb', 'test'+os.extsep+'rawimg'+os.extsep+'rev')
-
-ttob = rgbimg.ttob(0)
-if ttob != 1:
- raise error, 'ttob should be one'
-
-ttob = rgbimg.ttob(0)
-if ttob != 0:
- raise error, 'ttob should be zero'
-
-for source, target in table:
- unlink(findfile(target))
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
index 5158378..cfb293f 100644
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -124,7 +124,7 @@ class ThreadableTest:
self.server_ready.wait()
self.client_ready.set()
self.clientSetUp()
- if not callable(test_func):
+ if not hasattr(test_func, '__call__'):
raise TypeError, "test_func must be a callable function"
try:
test_func()
diff --git a/Lib/test/test_sundry.py b/Lib/test/test_sundry.py
index a37aad1..eb4149f 100644
--- a/Lib/test/test_sundry.py
+++ b/Lib/test/test_sundry.py
@@ -1,75 +1,72 @@
"""Do a minimal test of all the modules that aren't otherwise tested."""
+from test.test_support import guard_warnings_filter
import warnings
-warnings.filterwarnings('ignore', r".*posixfile module",
- DeprecationWarning, 'posixfile$')
-warnings.filterwarnings("ignore",
- "the gopherlib module is deprecated",
- DeprecationWarning,
- ".*test_sundry")
+with guard_warnings_filter():
+ warnings.filterwarnings('ignore', r".*posixfile",
+ DeprecationWarning)
-from test.test_support import verbose
+ from test.test_support import verbose
-import BaseHTTPServer
-import DocXMLRPCServer
-import CGIHTTPServer
-import SimpleHTTPServer
-import SimpleXMLRPCServer
-import aifc
-import audiodev
-import bdb
-import cgitb
-import cmd
-import code
-import compileall
-import encodings
-import formatter
-import ftplib
-import getpass
-import gopherlib
-import htmlentitydefs
-import ihooks
-import imghdr
-import imputil
-import keyword
-import linecache
-import macurl2path
-import mailcap
-import mimify
-import mutex
-import nntplib
-import nturl2path
-import opcode
-import os2emxpath
-import pdb
-import pipes
-#import poplib
-import posixfile
-import pstats
-import py_compile
-import pydoc
-import rlcompleter
-import sched
-import smtplib
-import sndhdr
-import statvfs
-import sunau
-import sunaudio
-import symbol
-import tabnanny
-import telnetlib
-import timeit
-import toaiff
-import token
-try:
- import tty # not available on Windows
-except ImportError:
- if verbose:
- print("skipping tty")
+ import BaseHTTPServer
+ import DocXMLRPCServer
+ import CGIHTTPServer
+ import SimpleHTTPServer
+ import SimpleXMLRPCServer
+ import aifc
+ import audiodev
+ import bdb
+ import cgitb
+ import cmd
+ import code
+ import compileall
+ import encodings
+ import formatter
+ import ftplib
+ import getpass
+ import htmlentitydefs
+ import ihooks
+ import imghdr
+ import imputil
+ import keyword
+ import linecache
+ import macurl2path
+ import mailcap
+ import mimify
+ import mutex
+ import nntplib
+ import nturl2path
+ import opcode
+ import os2emxpath
+ import pdb
+ import pipes
+ #import poplib
+ import posixfile
+ import pstats
+ import py_compile
+ import pydoc
+ import rlcompleter
+ import sched
+ import smtplib
+ import sndhdr
+ import statvfs
+ import sunau
+ import sunaudio
+ import symbol
+ import tabnanny
+ import telnetlib
+ import timeit
+ import toaiff
+ import token
+ try:
+ import tty # not available on Windows
+ except ImportError:
+ if verbose:
+ print("skipping tty")
-# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
-# can screw up all sorts of things (esp. if it prints!).
-#import user
-import webbrowser
-import xml
+ # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
+ # can screw up all sorts of things (esp. if it prints!).
+ #import user
+ import webbrowser
+ import xml
diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py
index a52c3dd..537b738 100644
--- a/Lib/test/test_urllib2net.py
+++ b/Lib/test/test_urllib2net.py
@@ -173,19 +173,6 @@ class OtherNetworkTests(unittest.TestCase):
]
self._test_urls(urls, self._extra_handlers())
- def test_gopher(self):
- import warnings
- warnings.filterwarnings("ignore",
- "the gopherlib module is deprecated",
- DeprecationWarning,
- "urllib2$")
- urls = [
- # Thanks to Fred for finding these!
- 'gopher://gopher.lib.ncsu.edu./11/library/stacks/Alex',
- 'gopher://gopher.vt.edu.:10010/10/33',
- ]
- self._test_urls(urls, self._extra_handlers())
-
def test_file(self):
TESTFN = test_support.TESTFN
f = open(TESTFN, 'w')
@@ -274,8 +261,6 @@ class OtherNetworkTests(unittest.TestCase):
def _extra_handlers(self):
handlers = []
- handlers.append(urllib2.GopherHandler)
-
cfh = urllib2.CacheFTPHandler()
cfh.setTimeout(1)
handlers.append(cfh)
diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py
index 3e214f8..4e21fd9 100644
--- a/Lib/test/test_xml_etree.py
+++ b/Lib/test/test_xml_etree.py
@@ -36,7 +36,7 @@ def sanity():
"""
def check_method(method):
- if not callable(method):
+ if not hasattr(method, '__call__'):
print(method, "not callable")
def serialize(ET, elem, encoding=None):
diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py
index d9760c6..1479247 100644
--- a/Lib/test/test_xml_etree_c.py
+++ b/Lib/test/test_xml_etree_c.py
@@ -34,7 +34,7 @@ def sanity():
"""
def check_method(method):
- if not callable(method):
+ if not hasattr(method, '__call__'):
print(method, "not callable")
def serialize(ET, elem, encoding=None):
diff --git a/Lib/test/time_hashlib.py b/Lib/test/time_hashlib.py
index 5b96d0e..df12f83 100644
--- a/Lib/test/time_hashlib.py
+++ b/Lib/test/time_hashlib.py
@@ -55,7 +55,7 @@ elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
print("testing speed of _hashlib.new(%r)" % sys.argv[2])
-elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
+elif hasattr(hashlib, hName) and hasattr(getattr(hashlib, hName), '__call__'):
creatorFunc = getattr(hashlib, hName)
print("testing speed of hashlib."+hName, getattr(hashlib, hName))
else:
diff --git a/Lib/timeit.py b/Lib/timeit.py
index a1a9b36..1d2bf08 100644
--- a/Lib/timeit.py
+++ b/Lib/timeit.py
@@ -126,7 +126,7 @@ class Timer:
if isinstance(setup, basestring):
setup = reindent(setup, 4)
src = template % {'stmt': stmt, 'setup': setup}
- elif callable(setup):
+ elif hasattr(setup, '__call__'):
src = template % {'stmt': stmt, 'setup': '_setup()'}
ns['_setup'] = setup
else:
@@ -135,13 +135,13 @@ class Timer:
code = compile(src, dummy_src_name, "exec")
exec(code, globals(), ns)
self.inner = ns["inner"]
- elif callable(stmt):
+ elif hasattr(stmt, '__call__'):
self.src = None
if isinstance(setup, basestring):
_setup = setup
def setup():
exec(_setup, globals(), ns)
- elif not callable(setup):
+ elif not hasattr(setup, '__call__'):
raise ValueError("setup is neither a string nor callable")
self.inner = _template_func(setup, stmt)
else:
diff --git a/Lib/unittest.py b/Lib/unittest.py
index 12017dd..46e2854 100644
--- a/Lib/unittest.py
+++ b/Lib/unittest.py
@@ -426,7 +426,7 @@ class TestSuite:
def addTest(self, test):
# sanity checks
- if not callable(test):
+ if not hasattr(test, '__call__'):
raise TypeError("the test to add must be callable")
if (isinstance(test, (type, types.ClassType)) and
issubclass(test, (TestCase, TestSuite))):
@@ -581,7 +581,7 @@ class TestLoader:
return TestSuite([parent(obj.__name__)])
elif isinstance(obj, TestSuite):
return obj
- elif callable(obj):
+ elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, TestSuite):
return test
@@ -604,7 +604,7 @@ class TestLoader:
"""Return a sorted sequence of method names found within testCaseClass
"""
def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
- return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
+ return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
testFnNames = filter(isTestMethod, dir(testCaseClass))
if self.sortTestMethodsUsing:
testFnNames.sort(self.sortTestMethodsUsing)
diff --git a/Lib/urllib.py b/Lib/urllib.py
index cffa026..6a7c23f 100644
--- a/Lib/urllib.py
+++ b/Lib/urllib.py
@@ -34,7 +34,7 @@ __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
"localhost", "thishost", "ftperrors", "basejoin", "unwrap",
"splittype", "splithost", "splituser", "splitpasswd", "splitport",
"splitnport", "splitquery", "splitattr", "splitvalue",
- "splitgophertype", "getproxies"]
+ "getproxies"]
__version__ = '1.17' # XXX This version is not always updated :-(
@@ -432,24 +432,6 @@ class URLopener:
return self.http_error(url, fp, errcode, errmsg, headers,
data)
- def open_gopher(self, url):
- """Use Gopher protocol."""
- if not isinstance(url, str):
- raise IOError, ('gopher error', 'proxy support for gopher protocol currently not implemented')
- import gopherlib
- host, selector = splithost(url)
- if not host: raise IOError, ('gopher error', 'no host given')
- host = unquote(host)
- type, selector = splitgophertype(selector)
- selector, query = splitquery(selector)
- selector = unquote(selector)
- if query:
- query = unquote(query)
- fp = gopherlib.send_query(selector, query, host)
- else:
- fp = gopherlib.send_selector(selector, host)
- return addinfourl(fp, noheaders(), "gopher:" + url)
-
def open_file(self, url):
"""Use local file or FTP depending on form of URL."""
if not isinstance(url, str):
@@ -967,7 +949,6 @@ class addinfourl(addbase):
# splitattr('/path;attr1=value1;attr2=value2;...') ->
# '/path', ['attr1=value1', 'attr2=value2', ...]
# splitvalue('attr=value') --> 'attr', 'value'
-# splitgophertype('/Xselector') --> 'X', 'selector'
# unquote('abc%20def') -> 'abc def'
# quote('abc def') -> 'abc%20def')
@@ -1127,12 +1108,6 @@ def splitvalue(attr):
if match: return match.group(1, 2)
return attr, None
-def splitgophertype(selector):
- """splitgophertype('/Xselector') --> 'X', 'selector'."""
- if selector[:1] == '/' and selector[1:2]:
- return selector[1], selector[2:]
- return None, selector
-
_hextochr = dict(('%02x' % i, chr(i)) for i in range(256))
_hextochr.update(('%02X' % i, chr(i)) for i in range(256))
@@ -1469,7 +1444,6 @@ def test(args=[]):
'file:/etc/passwd',
'file://localhost/etc/passwd',
'ftp://ftp.gnu.org/pub/README',
-## 'gopher://gopher.micro.umn.edu/1/',
'http://www.python.org/index.html',
]
if hasattr(URLopener, "open_https"):
diff --git a/Lib/urllib2.py b/Lib/urllib2.py
index 4127485..8d44a0d 100644
--- a/Lib/urllib2.py
+++ b/Lib/urllib2.py
@@ -104,7 +104,7 @@ import bisect
from io import StringIO
from urllib import (unwrap, unquote, splittype, splithost, quote,
- addinfourl, splitport, splitgophertype, splitquery,
+ addinfourl, splitport, splitquery,
splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue)
# support for FileHandler, proxies via environment variables
@@ -161,9 +161,6 @@ class HTTPError(URLError, addinfourl):
def __str__(self):
return 'HTTP Error %s: %s' % (self.code, self.msg)
-class GopherError(URLError):
- pass
-
# copied from cookielib.py
_cut_port_re = re.compile(r":\d+$")
def request_host(request):
@@ -1337,22 +1334,3 @@ class CacheFTPHandler(FTPHandler):
del self.timeout[k]
break
self.soonest = min(list(self.timeout.values()))
-
-class GopherHandler(BaseHandler):
- def gopher_open(self, req):
- # XXX can raise socket.error
- import gopherlib # this raises DeprecationWarning in 2.5
- host = req.get_host()
- if not host:
- raise GopherError('no host given')
- host = unquote(host)
- selector = req.get_selector()
- type, selector = splitgophertype(selector)
- selector, query = splitquery(selector)
- selector = unquote(selector)
- if query:
- query = unquote(query)
- fp = gopherlib.send_query(selector, query, host)
- else:
- fp = gopherlib.send_selector(selector, host)
- return addinfourl(fp, noheaders(), req.get_full_url())