# HG changeset patch # Parent 2358a46b621e3dfd355edea0e9f3dc1af5cf5804 Issue #13258: Use callable() built-in for better performance. diff --git a/Lib/argparse.py b/Lib/argparse.py --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -93,10 +93,6 @@ from gettext import gettext as _, ngettext -def _callable(obj): - return hasattr(obj, '__call__') or hasattr(obj, '__bases__') - - SUPPRESS = '==SUPPRESS==' OPTIONAL = '?' @@ -1311,13 +1307,13 @@ # create the action object, and add it to the parser action_class = self._pop_action_class(kwargs) - if not _callable(action_class): + if not callable(action_class): raise ValueError('unknown action "%s"' % (action_class,)) action = action_class(**kwargs) # raise an error if the action type is not callable type_func = self._registry_get('type', action.type, action.type) - if not _callable(type_func): + if not callable(type_func): raise ValueError('%r is not callable' % (type_func,)) # raise an error if the metavar does not match the type @@ -2260,7 +2256,7 @@ def _get_value(self, action, arg_string): type_func = self._registry_get('type', action.type, action.type) - if not _callable(type_func): + if not callable(type_func): msg = _('%r is not callable') raise ArgumentError(action, msg % type_func) diff --git a/Lib/copyreg.py b/Lib/copyreg.py --- a/Lib/copyreg.py +++ b/Lib/copyreg.py @@ -10,7 +10,7 @@ dispatch_table = {} def pickle(ob_type, pickle_function, constructor_ob=None): - if not hasattr(pickle_function, '__call__'): + if not callable(pickle_function): raise TypeError("reduction functions must be callable") dispatch_table[ob_type] = pickle_function @@ -20,7 +20,7 @@ constructor(constructor_ob) def constructor(object): - if not hasattr(object, '__call__'): + if not callable(object): 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 --- a/Lib/distutils/dist.py +++ b/Lib/distutils/dist.py @@ -537,7 +537,7 @@ for (help_option, short, desc, func) in cmd_class.help_options: if hasattr(opts, parser.get_attr_name(help_option)): help_option_found=1 - if hasattr(func, '__call__'): + if callable(func): func() else: raise DistutilsClassError( diff --git a/Lib/encodings/__init__.py b/Lib/encodings/__init__.py --- a/Lib/encodings/__init__.py +++ b/Lib/encodings/__init__.py @@ -120,12 +120,11 @@ if not 4 <= len(entry) <= 7: raise CodecRegistryError('module "%s" (%s) failed to register' % (mod.__name__, mod.__file__)) - 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__')): + 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])): raise CodecRegistryError('incompatible codecs in module "%s" (%s)' % (mod.__name__, mod.__file__)) if len(entry)<7 or entry[6] is None: diff --git a/Lib/fileinput.py b/Lib/fileinput.py --- a/Lib/fileinput.py +++ b/Lib/fileinput.py @@ -225,10 +225,11 @@ raise ValueError("FileInput opening mode must be one of " "'r', 'rU', 'U' and 'rb'") self._mode = mode - if inplace and openhook: - raise ValueError("FileInput cannot use an opening hook in inplace mode") - elif openhook and not hasattr(openhook, '__call__'): - raise ValueError("FileInput openhook must be callable") + if openhook: + if inplace: + raise ValueError("FileInput cannot use an opening hook in inplace mode") + if not callable(openhook): + raise ValueError("FileInput openhook must be callable") self._openhook = openhook def __del__(self): diff --git a/Lib/hmac.py b/Lib/hmac.py --- a/Lib/hmac.py +++ b/Lib/hmac.py @@ -39,7 +39,7 @@ import hashlib digestmod = hashlib.md5 - if hasattr(digestmod, '__call__'): + if callable(digestmod): self.digest_cons = digestmod else: self.digest_cons = lambda d=b'': digestmod.new(d) diff --git a/Lib/idlelib/rpc.py b/Lib/idlelib/rpc.py --- a/Lib/idlelib/rpc.py +++ b/Lib/idlelib/rpc.py @@ -574,7 +574,7 @@ # Adds names to dictionary argument 'methods' for name in dir(obj): attr = getattr(obj, name) - if hasattr(attr, '__call__'): + if callable(attr): methods[name] = 1 if isinstance(obj, type): for super in obj.__bases__: @@ -583,7 +583,7 @@ def _getattributes(obj, attributes): for name in dir(obj): attr = getattr(obj, name) - if not hasattr(attr, '__call__'): + if not callable(attr): attributes[name] = 1 class MethodProxy(object): diff --git a/Lib/logging/config.py b/Lib/logging/config.py --- a/Lib/logging/config.py +++ b/Lib/logging/config.py @@ -471,7 +471,7 @@ def configure_custom(self, config): """Configure an object with a user-supplied factory.""" c = config.pop('()') - if not hasattr(c, '__call__'): + if not callable(c): c = self.resolve(c) props = config.pop('.', None) # Check for valid identifiers @@ -690,7 +690,7 @@ filters = config.pop('filters', None) if '()' in config: c = config.pop('()') - if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: + if not callable(c): c = self.resolve(c) factory = c else: diff --git a/Lib/multiprocessing/managers.py b/Lib/multiprocessing/managers.py --- a/Lib/multiprocessing/managers.py +++ b/Lib/multiprocessing/managers.py @@ -134,7 +134,7 @@ temp = [] for name in dir(obj): func = getattr(obj, name) - if hasattr(func, '__call__'): + if callable(func): temp.append(name) return temp @@ -510,7 +510,7 @@ ''' assert self._state.value == State.INITIAL - if initializer is not None and not hasattr(initializer, '__call__'): + if initializer is not None and not callable(initializer): raise TypeError('initializer must be a callable') # pipe over which we will retrieve address of server diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -151,7 +151,7 @@ if processes < 1: raise ValueError("Number of processes must be at least 1") - if initializer is not None and not hasattr(initializer, '__call__'): + if initializer is not None and not callable(initializer): raise TypeError('initializer must be a callable') self._processes = processes diff --git a/Lib/optparse.py b/Lib/optparse.py --- a/Lib/optparse.py +++ b/Lib/optparse.py @@ -708,7 +708,7 @@ def _check_callback(self): if self.action == "callback": - if not hasattr(self.callback, '__call__'): + if not callable(self.callback): raise OptionError( "callback not callable: %r" % self.callback, self) if (self.callback_args is not None and diff --git a/Lib/packaging/dist.py b/Lib/packaging/dist.py --- a/Lib/packaging/dist.py +++ b/Lib/packaging/dist.py @@ -409,6 +409,7 @@ for help_option, short, desc, func in cmd_class.help_options: if hasattr(opts, help_option.replace('-', '_')): help_option_found = True + # Do not use callable() for compatibility with Python 3.1 if hasattr(func, '__call__'): func() else: @@ -733,6 +734,7 @@ else: hook_obj = hook + # Do not use callable() for compatibility with Python 3.1 if not hasattr(hook_obj, '__call__'): raise PackagingOptionError('hook %r is not callable' % hook) diff --git a/Lib/packaging/run.py b/Lib/packaging/run.py --- a/Lib/packaging/run.py +++ b/Lib/packaging/run.py @@ -500,6 +500,7 @@ for help_option, short, desc, func in cmd_class.help_options: if hasattr(opts, help_option.replace('-', '_')): help_option_found = True + # Do not use callable() for compatibility with Python 3.1 if hasattr(func, '__call__'): func() else: diff --git a/Lib/pickle.py b/Lib/pickle.py --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -362,7 +362,7 @@ raise PicklingError("args from save_reduce() should be a tuple") # Assert that func is callable - if not hasattr(func, '__call__'): + if not callable(func): raise PicklingError("func from save_reduce() should be callable") save = self.save diff --git a/Lib/pydoc.py b/Lib/pydoc.py --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -769,7 +769,7 @@ push(msg) for name, kind, homecls, value in ok: base = self.docother(getattr(object, name), name, mod) - if hasattr(value, '__call__') or inspect.isdatadescriptor(value): + if callable(value) or inspect.isdatadescriptor(value): doc = getattr(value, "__doc__", None) else: doc = None @@ -1196,7 +1196,7 @@ hr.maybe() push(msg) for name, kind, homecls, value in ok: - if hasattr(value, '__call__') or inspect.isdatadescriptor(value): + if callable(value) or inspect.isdatadescriptor(value): doc = getdoc(value) else: doc = None diff --git a/Lib/re.py b/Lib/re.py --- a/Lib/re.py +++ b/Lib/re.py @@ -325,7 +325,7 @@ if i == j: break action = self.lexicon[m.lastindex-1][1] - if hasattr(action, "__call__"): + if callable(action): self.match = m action = action(self, m.group()) if action is not None: diff --git a/Lib/rlcompleter.py b/Lib/rlcompleter.py --- a/Lib/rlcompleter.py +++ b/Lib/rlcompleter.py @@ -87,7 +87,7 @@ return None def _callable_postfix(self, val, word): - if hasattr(val, '__call__'): + if callable(val): word = word + "(" return word diff --git a/Lib/shutil.py b/Lib/shutil.py --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -525,7 +525,7 @@ """ if extra_args is None: extra_args = [] - if not isinstance(function, collections.Callable): + if not callable(function): raise TypeError('The %s object is not callable' % function) if not isinstance(extra_args, (tuple, list)): raise TypeError('extra_args needs to be a sequence') @@ -618,7 +618,7 @@ raise RegistryError(msg % (extension, existing_extensions[extension])) - if not isinstance(function, collections.Callable): + if not callable(function): raise TypeError('The registered function must be a callable') diff --git a/Lib/test/test_nntplib.py b/Lib/test/test_nntplib.py --- a/Lib/test/test_nntplib.py +++ b/Lib/test/test_nntplib.py @@ -5,7 +5,6 @@ import unittest import functools import contextlib -import collections.abc from test import support from nntplib import NNTP, GroupInfo, _have_ssl import nntplib @@ -247,7 +246,7 @@ if not name.startswith('test_'): continue meth = getattr(cls, name) - if not isinstance(meth, collections.abc.Callable): + if not callable(meth): continue # Need to use a closure so that meth remains bound to its current # value diff --git a/Lib/timeit.py b/Lib/timeit.py --- a/Lib/timeit.py +++ b/Lib/timeit.py @@ -127,7 +127,7 @@ if isinstance(setup, str): setup = reindent(setup, 4) src = template.format(stmt=stmt, setup=setup) - elif hasattr(setup, '__call__'): + elif callable(setup): src = template.format(stmt=stmt, setup='_setup()') ns['_setup'] = setup else: @@ -136,13 +136,13 @@ code = compile(src, dummy_src_name, "exec") exec(code, globals(), ns) self.inner = ns["inner"] - elif hasattr(stmt, '__call__'): + elif callable(stmt): self.src = None if isinstance(setup, str): _setup = setup def setup(): exec(_setup, globals(), ns) - elif not hasattr(setup, '__call__'): + elif not callable(setup): raise ValueError("setup is neither a string nor callable") self.inner = _template_func(setup, stmt) else: diff --git a/Lib/tkinter/__init__.py b/Lib/tkinter/__init__.py --- a/Lib/tkinter/__init__.py +++ b/Lib/tkinter/__init__.py @@ -1037,7 +1037,7 @@ for k, v in cnf.items(): if v is not None: if k[-1] == '_': k = k[:-1] - if hasattr(v, '__call__'): + if callable(v): v = self._register(v) elif isinstance(v, (tuple, list)): nv = [] @@ -1606,7 +1606,7 @@ """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 hasattr(func, '__call__'): + if callable(func): command = self._register(func) else: command = func @@ -3176,7 +3176,7 @@ elif kw: cnf = kw options = () for k, v in cnf.items(): - if hasattr(v, '__call__'): + if callable(v): v = self._register(v) options = options + ('-'+k, v) self.tk.call(('image', 'create', imgtype, name,) + options) @@ -3199,7 +3199,7 @@ for k, v in _cnfmerge(kw).items(): if v is not None: if k[-1] == '_': k = k[:-1] - if hasattr(v, '__call__'): + if callable(v): v = self._register(v) res = res + ('-'+k, v) self.tk.call((self.name, 'config') + res) diff --git a/Lib/tkinter/tix.py b/Lib/tkinter/tix.py --- a/Lib/tkinter/tix.py +++ b/Lib/tkinter/tix.py @@ -405,7 +405,7 @@ elif kw: cnf = kw options = () for k, v in cnf.items(): - if hasattr(v, '__call__'): + if callable(v): v = self._register(v) options = options + ('-'+k, v) return master.tk.call(('image', 'create', imgtype,) + options) diff --git a/Lib/unittest/loader.py b/Lib/unittest/loader.py --- a/Lib/unittest/loader.py +++ b/Lib/unittest/loader.py @@ -113,7 +113,7 @@ return self.suiteClass([inst]) elif isinstance(obj, suite.TestSuite): return obj - if hasattr(obj, '__call__'): + if callable(obj): test = obj() if isinstance(test, suite.TestSuite): return test @@ -138,7 +138,7 @@ def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix): return attrname.startswith(prefix) and \ - hasattr(getattr(testCaseClass, attrname), '__call__') + callable(getattr(testCaseClass, attrname)) testFnNames = testFnNames = list(filter(isTestMethod, dir(testCaseClass))) if self.sortTestMethodsUsing: diff --git a/Lib/unittest/suite.py b/Lib/unittest/suite.py --- a/Lib/unittest/suite.py +++ b/Lib/unittest/suite.py @@ -42,7 +42,7 @@ def addTest(self, test): # sanity checks - if not hasattr(test, '__call__'): + if not callable(test): raise TypeError("{} is not callable".format(repr(test))) if isinstance(test, type) and issubclass(test, (case.TestCase, TestSuite)): diff --git a/Lib/warnings.py b/Lib/warnings.py --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -259,7 +259,7 @@ raise RuntimeError( "Unrecognized action (%r) in warnings.filters:\n %s" % (action, item)) - if not hasattr(showwarning, "__call__"): + if not callable(showwarning): raise TypeError("warnings.showwarning() must be set to a " "function or method") # Print message and context diff --git a/Lib/xmlrpc/server.py b/Lib/xmlrpc/server.py --- a/Lib/xmlrpc/server.py +++ b/Lib/xmlrpc/server.py @@ -149,7 +149,7 @@ return [member for member in dir(obj) if not member.startswith('_') and - hasattr(getattr(obj, member), '__call__')] + callable(getattr(obj, member))] class SimpleXMLRPCDispatcher: """Mix-in class that dispatches XML-RPC requests.