bpo-30152: Reduce the number of imports for argparse. (#1269)
diff --git a/Lib/argparse.py b/Lib/argparse.py
index 98bbed0..d8bbd35 100644
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -84,15 +84,12 @@
import collections as _collections
-import copy as _copy
import os as _os
import re as _re
import sys as _sys
-import textwrap as _textwrap
from gettext import gettext as _, ngettext
-
SUPPRESS = '==SUPPRESS=='
OPTIONAL = '?'
@@ -137,10 +134,16 @@
return []
-def _ensure_value(namespace, name, value):
- if getattr(namespace, name, None) is None:
- setattr(namespace, name, value)
- return getattr(namespace, name)
+def _copy_items(items):
+ if items is None:
+ return []
+ # The copy module is used only in the 'append' and 'append_const'
+ # actions, and it is needed only when the default value isn't a list.
+ # Delay its import for speeding up the common case.
+ if type(items) is list:
+ return items[:]
+ import copy
+ return copy.copy(items)
# ===============
@@ -619,12 +622,17 @@
def _split_lines(self, text, width):
text = self._whitespace_matcher.sub(' ', text).strip()
- return _textwrap.wrap(text, width)
+ # The textwrap module is used only for formatting help.
+ # Delay its import for speeding up the common usage of argparse.
+ import textwrap
+ return textwrap.wrap(text, width)
def _fill_text(self, text, width, indent):
text = self._whitespace_matcher.sub(' ', text).strip()
- return _textwrap.fill(text, width, initial_indent=indent,
- subsequent_indent=indent)
+ import textwrap
+ return textwrap.fill(text, width,
+ initial_indent=indent,
+ subsequent_indent=indent)
def _get_help_string(self, action):
return action.help
@@ -952,7 +960,8 @@
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
- items = _copy.copy(_ensure_value(namespace, self.dest, []))
+ items = getattr(namespace, self.dest, None)
+ items = _copy_items(items)
items.append(values)
setattr(namespace, self.dest, items)
@@ -978,7 +987,8 @@
metavar=metavar)
def __call__(self, parser, namespace, values, option_string=None):
- items = _copy.copy(_ensure_value(namespace, self.dest, []))
+ items = getattr(namespace, self.dest, None)
+ items = _copy_items(items)
items.append(self.const)
setattr(namespace, self.dest, items)
@@ -1000,8 +1010,10 @@
help=help)
def __call__(self, parser, namespace, values, option_string=None):
- new_count = _ensure_value(namespace, self.dest, 0) + 1
- setattr(namespace, self.dest, new_count)
+ count = getattr(namespace, self.dest, None)
+ if count is None:
+ count = 0
+ setattr(namespace, self.dest, count + 1)
class _HelpAction(Action):