-
Notifications
You must be signed in to change notification settings - Fork 12
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support Literal types as an alternative means of specifying choices #46
Conversation
Support Literal types as an alternative means of specifying choices.
Test cases for the Literal type
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is great, thanks!
I think we'll probably want to check to avoid collisions between typing as Literal
and providing choices
. That case will also need a test to ensure proper behavior.
* Do not allow choices in the meta data when using a Literal type * Add test case
Hi Mike, Thanks for you fast reply and enthusiasm. I just committed a small change to address your concerns. You're right that a collision between using both a Literal type and having choices in the Metadata should be prevented. In my opinion, even when they would match because that kind of redundancy is error prone. But one might argue that it is desirable to allow the following: @dataclass
class Options:
a_or_b: Literal['a', 'b'] = field(metadata={choices : ['a', 'b']}) Now, I raise a ValueError when both are given. Even when valid. I also added a test case for that. What's your opinion on this? |
CI failures are due to |
Fix error in doctest: define Literal
Apparently, there are small differences in handling white space lines between the VSCode Black plugin and the command line script :(. |
Thanks! |
This PR adds support for using a
Literal
type to specify a fixed number of argument choices. This feature is intended as a improvement over the use of thechoices
field of themetadata
.Example usage
Rationale
Specifying choices using a type rather than via the metadata field has two advantages.
Literal
type instead of a more generic type (int
,float
,str
) for a limit set of options narrows the type specification and makes optimum use of the functionality of type checkers such as mypy.Considerations
Literal
type is supported from Python 3.8. As dropping support for earlier versions of Python is already anticipated on in Drop support for Python 3.6, 3.7 #39, no time was spend on testing this in older Python versions.metadata['choices']
is still possible and has precedence over the use of theLiteral
type.Content of PR
Literal
type added toargparse_dataclass._add_dataclass_options()
tests/test_argumentparser.py
README.rst
on the use of choices.P.S. Thank you very much for developing and sharing this highly useful module! Highly appreciated.