summaryrefslogtreecommitdiffstats
path: root/Doc/library/optparse.rst
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2008-12-15 09:07:39 (GMT)
committerGeorg Brandl <georg@python.org>2008-12-15 09:07:39 (GMT)
commit60b2e38b68e484830e3e3857197b0d9201c3ac22 (patch)
tree1beafaf01d154f0ca58d90999c8f1300373a813d /Doc/library/optparse.rst
parent2d2fe572a4605d3c25055717c1033589e2889e65 (diff)
downloadcpython-60b2e38b68e484830e3e3857197b0d9201c3ac22.zip
cpython-60b2e38b68e484830e3e3857197b0d9201c3ac22.tar.gz
cpython-60b2e38b68e484830e3e3857197b0d9201c3ac22.tar.bz2
#4568: remove limitation in varargs callback example.
Diffstat (limited to 'Doc/library/optparse.rst')
-rw-r--r--Doc/library/optparse.rst47
1 files changed, 22 insertions, 25 deletions
diff --git a/Doc/library/optparse.rst b/Doc/library/optparse.rst
index 311655d..fbc2de2 100644
--- a/Doc/library/optparse.rst
+++ b/Doc/library/optparse.rst
@@ -1630,36 +1630,33 @@ directly).
Nevertheless, here's a stab at a callback for an option with variable
arguments::
- def vararg_callback(option, opt_str, value, parser):
- assert value is None
- done = 0
- value = []
- rargs = parser.rargs
- while rargs:
- arg = rargs[0]
-
- # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
- # etc. Note that this also stops on "-3" or "-3.0", so if
- # your option takes numeric values, you will need to handle
- # this.
- if ((arg[:2] == "--" and len(arg) > 2) or
- (arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")):
- break
- else:
- value.append(arg)
- del rargs[0]
-
- setattr(parser.values, option.dest, value)
+ def vararg_callback(option, opt_str, value, parser):
+ assert value is None
+ value = []
+
+ def floatable(str):
+ try:
+ float(str)
+ return True
+ except ValueError:
+ return False
+
+ for arg in parser.rargs:
+ # stop on --foo like options
+ if arg[:2] == "--" and len(arg) > 2:
+ break
+ # stop on -a, but not on -3 or -3.0
+ if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
+ break
+ value.append(arg)
+
+ del parser.rargs[:len(value)]
+ setattr(parser.values, option.dest, value))
[...]
parser.add_option("-c", "--callback", dest="vararg_attr",
action="callback", callback=vararg_callback)
-The main weakness with this particular implementation is that negative numbers
-in the arguments following ``"-c"`` will be interpreted as further options
-(probably causing an error), rather than as arguments to ``"-c"``. Fixing this
-is left as an exercise for the reader.
-
.. _optparse-extending-optparse: