[issue16516] argparse types (and actions) must be hashable

paul j3 report at bugs.python.org
Sun Jul 13 00:22:35 CEST 2014


paul j3 added the comment:

This is a straight forward patch, modifying '_registry_get' to return 'default' if it gets this 'TypeError'.  'test_argparse.py' has a testcase based on jnothman's example.  Temporarily it includes a skipped test that would pass the original code.

The alternative would be to add a note to the documentation to the effect that the 'type' must also be hashable.  But for an edge condition like this, that may be more confusing than enlightening.

While 'dict(one=1, two=20).get' now works as a 'type' callable, it is not ideal.  If there is no match it returns None.  The alternative '.__getitem__' raises a KeyError.  But '_get_values' handles TypeError and ValueErrors, the kinds returned by 'int' and 'float'.  It also handles an ArgumentTypeError, giving a custom type more control over the error message.  Is it worth noting something about the type errors in the documentation?

I've seen users make a different error with the type parameter - 'type=boolean', thinking this means the input should be converted to boolean.  They are thinking of 'type' as a datatype, rather than a function that converts a string into something else.  I don't know of a solution other than explaining that 'boolean()' does not act like 'int()'.

This patch also handles the 'action' case.  However I can't think of a way write a Action subclass that would be unhashable.  It would have to inherit from both Action and dict.

----------
keywords: +patch
Added file: http://bugs.python.org/file35936/patch.diff

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16516>
_______________________________________


More information about the Python-bugs-list mailing list