summaryrefslogtreecommitdiff
path: root/numpy/core/overrides.py
diff options
context:
space:
mode:
authorMark Harfouche <mark.harfouche@gmail.com>2019-07-25 20:46:13 -0400
committerSebastian Berg <sebastian@sipsolutions.net>2019-07-25 17:46:13 -0700
commit702c357536c23d8122fe152f0d86b9add1add6a0 (patch)
treef66c914db2107d1a993cfaedc00b9b81f7181a70 /numpy/core/overrides.py
parentf6f7995b485d5b9895cd456815192abe10ac6fcb (diff)
downloadnumpy-702c357536c23d8122fe152f0d86b9add1add6a0.tar.gz
MAINT: import time: avoid repeated textwrap function dispatch instantiation
Avoid the repeated call of `dedent` when a single call is enough. This micro-optimizes the import time from around 100ms (or slightly above) by 4-6 ms. (PR: gh-14095)
Diffstat (limited to 'numpy/core/overrides.py')
-rw-r--r--numpy/core/overrides.py20
1 files changed, 13 insertions, 7 deletions
diff --git a/numpy/core/overrides.py b/numpy/core/overrides.py
index 04a5a995f..55c7bd1ea 100644
--- a/numpy/core/overrides.py
+++ b/numpy/core/overrides.py
@@ -109,6 +109,18 @@ def set_module(module):
return decorator
+
+# Call textwrap.dedent here instead of in the function so as to avoid
+# calling dedent multiple times on the same text
+_wrapped_func_source = textwrap.dedent("""
+ @functools.wraps(implementation)
+ def {name}(*args, **kwargs):
+ relevant_args = dispatcher(*args, **kwargs)
+ return implement_array_function(
+ implementation, {name}, relevant_args, args, kwargs)
+ """)
+
+
def array_function_dispatch(dispatcher, module=None, verify=True,
docs_from_dispatcher=False):
"""Decorator for adding dispatch with the __array_function__ protocol.
@@ -163,13 +175,7 @@ def array_function_dispatch(dispatcher, module=None, verify=True,
# more interpettable name. Otherwise, the original function does not
# show up at all in many cases, e.g., if it's written in C or if the
# dispatcher gets an invalid keyword argument.
- source = textwrap.dedent("""
- @functools.wraps(implementation)
- def {name}(*args, **kwargs):
- relevant_args = dispatcher(*args, **kwargs)
- return implement_array_function(
- implementation, {name}, relevant_args, args, kwargs)
- """).format(name=implementation.__name__)
+ source = _wrapped_func_source.format(name=implementation.__name__)
source_object = compile(
source, filename='<__array_function__ internals>', mode='exec')