Get rid of many apply() calls.

This commit is contained in:
Guido van Rossum 2003-02-27 20:14:51 +00:00
parent f389c77273
commit 68468eba63
38 changed files with 85 additions and 91 deletions

View File

@ -415,7 +415,7 @@ class BaseHTTPRequestHandler(SocketServer.StreamRequestHandler):
"""
apply(self.log_message, args)
self.log_message(*args)
def log_message(self, format, *args):
"""Log an arbitrary message.

View File

@ -77,7 +77,7 @@ class UserList:
def count(self, item): return self.data.count(item)
def index(self, item): return self.data.index(item)
def reverse(self): self.data.reverse()
def sort(self, *args): apply(self.data.sort, args)
def sort(self, *args): self.data.sort(*args)
def extend(self, other):
if isinstance(other, UserList):
self.data.extend(other.data)

View File

@ -17,7 +17,7 @@ def _run_exitfuncs():
while _exithandlers:
func, targs, kargs = _exithandlers.pop()
apply(func, targs, kargs)
func(*targs, **kargs)
def register(func, *targs, **kargs):
"""register a function to be executed upon normal program termination

View File

@ -385,7 +385,7 @@ class Bdb:
res = None
try:
try:
res = apply(func, args)
res = func(*args)
except BdbQuit:
pass
finally:

View File

@ -88,7 +88,7 @@ def initlog(*allargs):
log = nolog
else:
log = dolog
apply(log, allargs)
log(*allargs)
def dolog(fmt, *args):
"""Write a log message to the log file. See initlog() for docs."""

View File

@ -140,7 +140,7 @@ def _copy_inst(x):
return x.__copy__()
if hasattr(x, '__getinitargs__'):
args = x.__getinitargs__()
y = apply(x.__class__, args)
y = x.__class__(*args)
else:
y = _EmptyClass()
y.__class__ = x.__class__
@ -293,7 +293,7 @@ def _deepcopy_inst(x, memo):
if hasattr(x, '__getinitargs__'):
args = x.__getinitargs__()
args = deepcopy(args, memo)
y = apply(x.__class__, args)
y = x.__class__(*args)
else:
y = _EmptyClass()
y.__class__ = x.__class__

View File

@ -108,7 +108,7 @@ class AbstractFormatter:
def add_hor_rule(self, *args, **kw):
if not self.hard_break:
self.writer.send_line_break()
apply(self.writer.send_hor_rule, args, kw)
self.writer.send_hor_rule(*args, **kw)
self.hard_break = self.nospace = 1
self.have_label = self.para_end = self.softspace = self.parskip = 0

View File

@ -83,7 +83,7 @@ class _Verbose:
def note(self, *args):
if self.verbose:
apply(self.message, args)
self.message(*args)
def message(self, format, *args):
if args:
@ -194,7 +194,7 @@ class Hooks(_Verbose):
def path_islink(self, x): return os.path.islink(x)
# etc.
def openfile(self, *x): return apply(open, x)
def openfile(self, *x): return open(*x)
openfile_error = IOError
def listdir(self, x): return os.listdir(x)
listdir_error = os.error

View File

@ -579,9 +579,9 @@ class IMAP4:
"""
name = 'SEARCH'
if charset:
typ, dat = apply(self._simple_command, (name, 'CHARSET', charset) + criteria)
typ, dat = self._simple_command(name, 'CHARSET', charset, *criteria)
else:
typ, dat = apply(self._simple_command, (name,) + criteria)
typ, dat = self._simple_command(name, *criteria)
return self._untagged_response(typ, dat, name)
@ -642,7 +642,7 @@ class IMAP4:
# raise self.error('unimplemented extension command: %s' % name)
if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
sort_criteria = '(%s)' % sort_criteria
typ, dat = apply(self._simple_command, (name, sort_criteria, charset) + search_criteria)
typ, dat = self._simple_command(name, sort_criteria, charset, *search_criteria)
return self._untagged_response(typ, dat, name)
@ -692,7 +692,7 @@ class IMAP4:
raise self.error('command %s illegal in state %s'
% (command, self.state))
name = 'UID'
typ, dat = apply(self._simple_command, (name, command) + args)
typ, dat = self._simple_command(name, command, *args)
if command in ('SEARCH', 'SORT'):
name = command
else:
@ -723,7 +723,7 @@ class IMAP4:
# raise self.error('unknown extension command: %s' % name)
if not name in Commands:
Commands[name] = (self.state,)
return apply(self._simple_command, (name,) + args)
return self._simple_command(name, *args)
@ -995,7 +995,7 @@ class IMAP4:
def _simple_command(self, name, *args):
return self._command_complete(name, apply(self._command, (name,) + args))
return self._command_complete(name, self._command(name, *args))
def _untagged_response(self, typ, dat, name):
@ -1040,7 +1040,7 @@ class IMAP4:
i, n = self._cmd_log_idx, self._cmd_log_len
while n:
try:
apply(self._mesg, self._cmd_log[i])
self._mesg(*self._cmd_log[i])
except:
pass
i += 1
@ -1390,7 +1390,7 @@ if __name__ == '__main__':
def run(cmd, args):
M._mesg('%s %s' % (cmd, args))
typ, dat = apply(getattr(M, cmd), args)
typ, dat = getattr(M, cmd)(*args)
M._mesg('%s => %s %s' % (cmd, typ, dat))
if typ == 'NO': raise dat[0]
return dat

View File

@ -874,7 +874,7 @@ class Logger(Filterer):
if self.manager.disable >= DEBUG:
return
if DEBUG >= self.getEffectiveLevel():
apply(self._log, (DEBUG, msg, args), kwargs)
self._log(DEBUG, msg, args, **kwargs)
def info(self, msg, *args, **kwargs):
"""
@ -888,7 +888,7 @@ class Logger(Filterer):
if self.manager.disable >= INFO:
return
if INFO >= self.getEffectiveLevel():
apply(self._log, (INFO, msg, args), kwargs)
self._log(INFO, msg, args, **kwargs)
def warning(self, msg, *args, **kwargs):
"""
@ -902,7 +902,7 @@ class Logger(Filterer):
if self.manager.disable >= WARNING:
return
if self.isEnabledFor(WARNING):
apply(self._log, (WARNING, msg, args), kwargs)
self._log(WARNING, msg, args, **kwargs)
warn = warning
@ -918,13 +918,13 @@ class Logger(Filterer):
if self.manager.disable >= ERROR:
return
if self.isEnabledFor(ERROR):
apply(self._log, (ERROR, msg, args), kwargs)
self._log(ERROR, msg, args, **kwargs)
def exception(self, msg, *args):
"""
Convenience method for logging an ERROR with exception information.
"""
apply(self.error, (msg,) + args, {'exc_info': 1})
self.error(msg, exc_info=1, *args)
def critical(self, msg, *args, **kwargs):
"""
@ -938,7 +938,7 @@ class Logger(Filterer):
if self.manager.disable >= CRITICAL:
return
if CRITICAL >= self.getEffectiveLevel():
apply(self._log, (CRITICAL, msg, args), kwargs)
self._log(CRITICAL, msg, args, **kwargs)
fatal = critical
@ -954,7 +954,7 @@ class Logger(Filterer):
if self.manager.disable >= level:
return
if self.isEnabledFor(level):
apply(self._log, (level, msg, args), kwargs)
self._log(level, msg, args, **kwargs)
def findCaller(self):
"""
@ -1131,7 +1131,7 @@ def critical(msg, *args, **kwargs):
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.critical, (msg,)+args, kwargs)
root.critical(msg, *args, **kwargs)
fatal = critical
@ -1141,14 +1141,14 @@ def error(msg, *args, **kwargs):
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.error, (msg,)+args, kwargs)
root.error(msg, *args, **kwargs)
def exception(msg, *args):
"""
Log a message with severity 'ERROR' on the root logger,
with exception information.
"""
apply(error, (msg,)+args, {'exc_info': 1})
error(msg, exc_info=1, *args)
def warning(msg, *args, **kwargs):
"""
@ -1156,7 +1156,7 @@ def warning(msg, *args, **kwargs):
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.warning, (msg,)+args, kwargs)
root.warning(msg, *args, **kwargs)
warn = warning
@ -1166,7 +1166,7 @@ def info(msg, *args, **kwargs):
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.info, (msg,)+args, kwargs)
root.info(msg, *args, **kwargs)
def debug(msg, *args, **kwargs):
"""
@ -1174,7 +1174,7 @@ def debug(msg, *args, **kwargs):
"""
if len(root.handlers) == 0:
basicConfig()
apply(root.debug, (msg,)+args, kwargs)
root.debug(msg, *args, **kwargs)
def disable(level):
"""

View File

@ -102,7 +102,7 @@ def fileConfig(fname, defaults=None):
klass = eval(klass, vars(logging))
args = cp.get(sectname, "args")
args = eval(args, vars(logging))
h = apply(klass, args)
h = klass(*args)
if "level" in opts:
level = cp.get(sectname, "level")
h.setLevel(logging._levelNames[level])

View File

@ -251,7 +251,7 @@ class Folder:
def error(self, *args):
"""Error message handler."""
apply(self.mh.error, args)
self.mh.error(*args)
def getfullname(self):
"""Return the full pathname of the folder."""

View File

@ -461,4 +461,4 @@ if __name__ == '__main__' or (len(sys.argv) > 0 and sys.argv[0] == 'mimify'):
encode_args = (args[0], args[1])
if decode_base64:
encode_args = encode_args + (decode_base64,)
apply(encode, encode_args)
encode(*encode_args)

View File

@ -97,13 +97,13 @@ class ModuleFinder:
level = args[0]
if level <= self.debug:
self.indent = self.indent + 1
apply(self.msg, args)
self.msg(*args)
def msgout(self, *args):
level = args[0]
if level <= self.debug:
self.indent = self.indent - 1
apply(self.msg, args)
self.msg(*args)
def run_script(self, pathname):
self.msg(2, "run_script", pathname)

View File

@ -41,7 +41,7 @@ __all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError",
class NNTPError(Exception):
"""Base class for all nntplib exceptions"""
def __init__(self, *args):
apply(Exception.__init__, (self,)+args)
Exception.__init__(self, *args)
try:
self.response = args[0]
except IndexError:

View File

@ -271,7 +271,7 @@ def _execvpe(file, args, env=None):
head, tail = path.split(file)
if head:
apply(func, (file,) + argrest)
func(file, *argrest)
return
if 'PATH' in env:
envpath = env['PATH']
@ -283,7 +283,7 @@ def _execvpe(file, args, env=None):
for dir in PATH:
fullname = path.join(dir, file)
try:
apply(func, (fullname,) + argrest)
func(fullname, *argrest)
except error, e:
tb = sys.exc_info()[2]
if (e.errno != ENOENT and e.errno != ENOTDIR

View File

@ -948,7 +948,7 @@ def runctx(statement, globals, locals):
run(statement, globals, locals)
def runcall(*args):
return apply(Pdb().runcall, args)
return Pdb().runcall(*args)
def set_trace():
Pdb().set_trace()

View File

@ -505,7 +505,7 @@ class RegexObject:
self.pattern = statetuple[0]
self.flags = statetuple[1]
self.groupindex = statetuple[2]
self.code = apply(pcre_compile, statetuple)
self.code = pcre_compile(*statetuple)
class _Dummy:
# Dummy class used by _subn_string(). Has 'group' to avoid core dump.

View File

@ -416,7 +416,7 @@ class Profile:
self.set_cmd(`func`)
sys.setprofile(self.dispatcher)
try:
return apply(func, args, kw)
return func(*args, **kw)
finally:
sys.setprofile(None)

View File

@ -76,7 +76,7 @@ class Stats:
arg = args[0]
args = args[1:]
self.init(arg)
apply(self.add, args)
self.add(*args)
def init(self, arg):
self.all_callees = None # calc only if needed
@ -134,7 +134,7 @@ class Stats:
def add(self, *arg_list):
if not arg_list: return self
if len(arg_list) > 1: apply(self.add, arg_list[1:])
if len(arg_list) > 1: self.add(*arg_list[1:])
other = arg_list[0]
if type(self) != type(other) or self.__class__ != other.__class__:
other = Stats(other)
@ -528,7 +528,7 @@ if __name__ == '__main__':
pass
processed.append(term)
if self.stats:
apply(getattr(self.stats, fn), processed)
getattr(self.stats, fn)(*processed)
else:
print "No statistics object is loaded."
return 0
@ -594,7 +594,7 @@ if __name__ == '__main__':
def do_sort(self, line):
abbrevs = self.stats.get_sort_arg_defs()
if line and not filter(lambda x,a=abbrevs: x not in a,line.split()):
apply(self.stats.sort_stats, line.split())
self.stats.sort_stats(*line.split())
else:
print "Valid sort keys (unique prefixes are accepted):"
for (key, value) in Stats.sort_arg_dict_default.iteritems():

View File

@ -163,7 +163,7 @@ def spawn(argv, master_read=_read, stdin_read=_read):
argv = (argv,)
pid, master_fd = fork()
if pid == CHILD:
apply(os.execlp, (argv[0],) + argv)
os.execlp(argv[0], *argv)
try:
mode = tty.tcgetattr(STDIN_FILENO)
tty.setraw(STDIN_FILENO)

View File

@ -266,10 +266,10 @@ class Doc:
def document(self, object, name=None, *args):
"""Generate documentation for an object."""
args = (object, name) + args
if inspect.ismodule(object): return apply(self.docmodule, args)
if inspect.isclass(object): return apply(self.docclass, args)
if inspect.isroutine(object): return apply(self.docroutine, args)
return apply(self.docother, args)
if inspect.ismodule(object): return self.docmodule(*args)
if inspect.isclass(object): return self.docclass(*args)
if inspect.isroutine(object): returnself.docroutine(*args)
return self.docother(*args)
def fail(self, object, name=None, *args):
"""Raise an exception for unimplemented types."""
@ -379,7 +379,7 @@ TT { font-family: lucidatypewriter, lucida console, courier }
def bigsection(self, title, *args):
"""Format a section with a big heading."""
title = '<big><strong>%s</strong></big>' % title
return apply(self.section, (title,) + args)
return self.section(title, *args)
def preformat(self, text):
"""Format literal preformatted text."""

View File

@ -48,7 +48,7 @@ class FileWrapper(FileBase):
TEMPLATE = """
def %s(self, *args):
return apply(getattr(self.mod, self.name).%s, args)
return getattr(self.mod, self.name).%s(*args)
"""
class FileDelegate(FileBase):
@ -407,14 +407,11 @@ class RExec(ihooks._Verbose):
sys.stdout = self.save_stdout
sys.stderr = self.save_stderr
def s_apply(self, func, args=(), kw=None):
def s_apply(self, func, args=(), kw={}):
self.save_files()
try:
self.set_files()
if kw:
r = apply(func, args, kw)
else:
r = apply(func, args)
r = func(*args, **kw)
finally:
self.restore_files()
return r

View File

@ -230,7 +230,7 @@ class Entry:
class URLopener(urllib.FancyURLopener):
def __init__(self, *args):
apply(urllib.FancyURLopener.__init__, (self,) + args)
urllib.FancyURLopener.__init__(self, *args)
self.errcode = 200
def http_error_default(self, url, fp, errcode, errmsg, headers):

View File

@ -102,5 +102,5 @@ class scheduler:
self.delayfunc(time - now)
else:
del q[0]
void = apply(action, argument)
void = action(*argument)
self.delayfunc(0) # Let other threads run

View File

@ -311,7 +311,7 @@ class Telnet:
s_args = s_reply
if timeout is not None:
s_args = s_args + (timeout,)
while not self.eof and apply(select.select, s_args) == s_reply:
while not self.eof and select.select(*s_args) == s_reply:
i = max(0, len(self.cookedq)-n)
self.fill_rawq()
self.process_rawq()

View File

@ -239,5 +239,5 @@ for name in ['za', 'zade', 'zabk', 'zabdv', 'zabdevk']:
kwdict = {}
for k in kwargs: kwdict[k] = k + k
print func.func_name, args, sortdict(kwdict), '->',
try: apply(func, args, kwdict)
try: func(*args, **kwdict)
except TypeError, err: print err

View File

@ -1,6 +1,5 @@
from test.test_support import TestFailed, verbose, verify
import struct
## import pdb
import sys
ISBIGENDIAN = sys.byteorder == "big"
@ -21,23 +20,21 @@ def bigendian_to_native(value):
def simple_err(func, *args):
try:
apply(func, args)
func(*args)
except struct.error:
pass
else:
raise TestFailed, "%s%s did not raise struct.error" % (
func.__name__, args)
## pdb.set_trace()
def any_err(func, *args):
try:
apply(func, args)
func(*args)
except (struct.error, OverflowError, TypeError):
pass
else:
raise TestFailed, "%s%s did not raise error" % (
func.__name__, args)
## pdb.set_trace()
simple_err(struct.calcsize, 'Z')

View File

@ -57,7 +57,7 @@ else:
Lock = _allocate_lock
def RLock(*args, **kwargs):
return apply(_RLock, args, kwargs)
return _RLock(*args, **kwargs)
class _RLock(_Verbose):
@ -128,7 +128,7 @@ class _RLock(_Verbose):
def Condition(*args, **kwargs):
return apply(_Condition, args, kwargs)
return _Condition(*args, **kwargs)
class _Condition(_Verbose):
@ -240,7 +240,7 @@ class _Condition(_Verbose):
def Semaphore(*args, **kwargs):
return apply(_Semaphore, args, kwargs)
return _Semaphore(*args, **kwargs)
class _Semaphore(_Verbose):
@ -282,7 +282,7 @@ class _Semaphore(_Verbose):
def BoundedSemaphore(*args, **kwargs):
return apply(_BoundedSemaphore, args, kwargs)
return _BoundedSemaphore(*args, **kwargs)
class _BoundedSemaphore(_Semaphore):
"""Semaphore that checks that # releases is <= # acquires"""
@ -297,7 +297,7 @@ class _BoundedSemaphore(_Semaphore):
def Event(*args, **kwargs):
return apply(_Event, args, kwargs)
return _Event(*args, **kwargs)
class _Event(_Verbose):
@ -396,7 +396,7 @@ class Thread(_Verbose):
def run(self):
if self.__target:
apply(self.__target, self.__args, self.__kwargs)
self.__target(*self.__args, **self.__kwargs)
def __bootstrap(self):
try:

View File

@ -42,8 +42,8 @@ tok_name[NL] = 'NL'
N_TOKENS += 2
def group(*choices): return '(' + '|'.join(choices) + ')'
def any(*choices): return apply(group, choices) + '*'
def maybe(*choices): return apply(group, choices) + '?'
def any(*choices): return group(*choices) + '*'
def maybe(*choices): return group(*choices) + '?'
Whitespace = r'[ \f\t]*'
Comment = r'#[^\r\n]*'
@ -157,7 +157,7 @@ def tokenize(readline, tokeneater=printtoken):
# backwards compatible interface
def tokenize_loop(readline, tokeneater):
for token_info in generate_tokens(readline):
apply(tokeneater, token_info)
tokeneater(*token_info)
def generate_tokens(readline):
"""

View File

@ -471,7 +471,7 @@ class Trace:
if not self.donothing:
sys.settrace(self.globaltrace)
try:
result = apply(func, args, kw)
result = func(*args, **kw)
finally:
if not self.donothing:
sys.settrace(None)

View File

@ -115,7 +115,7 @@ class TestResult:
def _exc_info_to_string(self, err):
"""Converts a sys.exc_info()-style tuple of values into a string."""
return string.join(apply(traceback.format_exception, err), '')
return string.join(traceback.format_exception(*err), '')
def __repr__(self):
return "<%s run=%i errors=%i failures=%i>" % \
@ -276,7 +276,7 @@ class TestCase:
unexpected exception.
"""
try:
apply(callableObj, args, kwargs)
callableObj(*args, **kwargs)
except excClass:
return
else:
@ -561,7 +561,7 @@ class _WritelnDecorator:
return getattr(self.stream,attr)
def writeln(self, *args):
if args: apply(self.write, args)
if args: self.write(*args)
self.write('\n') # text-mode streams translate to \r\n if needed

View File

@ -293,7 +293,7 @@ class URLopener:
h.putrequest('GET', selector)
if auth: h.putheader('Authorization', 'Basic %s' % auth)
if realhost: h.putheader('Host', realhost)
for args in self.addheaders: apply(h.putheader, args)
for args in self.addheaders: h.putheader(*args)
h.endheaders()
if data is not None:
h.send(data)
@ -371,7 +371,7 @@ class URLopener:
h.putrequest('GET', selector)
if auth: h.putheader('Authorization: Basic %s' % auth)
if realhost: h.putheader('Host', realhost)
for args in self.addheaders: apply(h.putheader, args)
for args in self.addheaders: h.putheader(*args)
h.endheaders()
if data is not None:
h.send(data)
@ -541,7 +541,7 @@ class FancyURLopener(URLopener):
"""Derived class with handlers for errors we can handle (perhaps)."""
def __init__(self, *args, **kwargs):
apply(URLopener.__init__, (self,) + args, kwargs)
URLopener.__init__(self, *args, **kwargs)
self.auth_cache = {}
self.tries = 0
self.maxtries = 10
@ -804,7 +804,7 @@ class addclosehook(addbase):
def close(self):
addbase.close(self)
if self.closehook:
apply(self.closehook, self.hookargs)
self.closehook(*self.hookargs)
self.closehook = None
self.hookargs = None

View File

@ -246,7 +246,7 @@ def _test():
for method, args in packtest:
print 'pack test', count,
try:
apply(method, args)
method(*args)
print 'succeeded'
except ConversionError, var:
print 'ConversionError:', var.msg
@ -272,7 +272,7 @@ def _test():
print 'unpack test', count,
try:
if succeedlist[count]:
x = apply(method, args)
x = method(*args)
print pred(x) and 'succeeded' or 'failed', ':', x
else:
print 'skipping'

View File

@ -66,7 +66,7 @@ class DOMException(Exception):
if self.__class__ is DOMException:
raise RuntimeError(
"DOMException should not be instantiated directly")
apply(Exception.__init__, (self,) + args, kw)
Exception.__init__(self, *args, **kw)
def _get_code(self):
return self.code

View File

@ -401,7 +401,7 @@ class ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):
# ---
def create_parser(*args, **kwargs):
return apply(ExpatParser, args, kwargs)
return ExpatParser(*args, **kwargs)
# ---

View File

@ -809,7 +809,7 @@ class TestXMLParser(XMLParser):
def __init__(self, **kw):
self.testdata = ""
apply(XMLParser.__init__, (self,), kw)
XMLParser.__init__(self, **kw)
def handle_xml(self, encoding, standalone):
self.flush()

View File

@ -720,7 +720,7 @@ class Unmarshaller:
if self._type is None or self._marks:
raise ResponseError()
if self._type == "fault":
raise apply(Fault, (), self._stack[0])
raise Fault(**self._stack[0])
return tuple(self._stack)
def getmethodname(self):
@ -1213,7 +1213,7 @@ class SafeTransport(Transport):
"your version of httplib doesn't support HTTPS"
)
else:
return apply(HTTPS, (host, None), x509 or {})
return HTTPS(host, None, **(x509 or {}))
##
# Standard server proxy. This class establishes a virtual connection