Comments (8)
This option, let's call it option 1:
class Args:
foo: Optionl[str]
bar: Optional[str]
Doesn't express the constraint that it's impossible for both options to be present. Logically it should be Optional[Union[Foo, Bar]]
where both Foo
and Bar
are classes with a single member, which is too verbose. (Optional[Union[str, str]]
doesn't make any sense, so both strings need a class to wrap them.)
However, considering again option 1 - while technically it's not type-safe, as explained, this small divergence between type checking and runtime seems rather benign. Meaning, I can't think of problems this is likely to create. I might be persuaded to include this if the interface is nice enough, but I will need to see a suggestion. One of my concerns is that I don't really like naming groups with a string like in your opening comment for this issue since it doesn't detect typos. It should be examined whether there are better alternatives.
from datargs.
Your example Args
class cannot be instantiated correctly. Its mutually exclusive arg group would have either foo
or bar
, but not both. However, the class Args
has both of these fields. In type theory terms one would say that this class is a product type, while it should really be a sum type. Sum types a represented by Union
in Python. However, as explained in the readme, the Union
type is reserved for subcommands.
Originally, this library was meant to save as much argparse
boilerplate as possible in the most common cases. My prime tendency is not to complicate it unnecessarily. However, if you'd like, you can try implementing something like this for me to consider:
EDIT: this example doesn't make sense, as explained in the following comments.
from datargs import argsclass, mutually_exclusive_group
@argsclass
class Group1:
foo: str
bar: str
@argsclass
class Group2:
baz: int
spam: int
@argsclass
class Args:
group: Union[Group1, Group2] = mutually_exclusive_group(required=True)
The implementation should probably be along these lines: mutually_exclusive_group()
would return a dataclass.field()
with an appropriate key in its metadata
, which _make_parser()
would check for and build the appropriate parser.
Note that an implementation should include appropriate tests and clear error messages for plausible user errors.
from datargs.
Thank you for the comment. But I did not understand very well.
I thought "mutually exclusive group" meant that only one of the arguments of the group can be present on the command line
Like in this example:
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group()
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args(['--foo'])
Namespace(bar=True, foo=True)
>>> parser.parse_args(['--bar'])
Namespace(bar=False, foo=False)
>>> parser.parse_args(['--foo', '--bar'])
usage: PROG [-h] [--foo | --bar]
PROG: error: argument --bar: not allowed with argument --foo
But, in your example, Group1
could be passed with the 2 arguments foo
and bar
without problem. Is that right?
from datargs.
In my example, the class Args
has both of these fields. But (in theory) only one of them could be present in the command line if they are in the mutually exclusive group (and maybe that requires a more complicated implementation)
from datargs.
I apologize, I haven't used mutually exclusive arguments in a while, so my example is incorrect. My comment about your suggestion, however, still stands: the class Args
has both foo
and bar
fields, but the program only accepts one of them on the command line. So when instantiating the class when foo
is passed, what would bar
hold? It would have to be None
, which is not a member of bar
's type. This could be circumvented by having both foo
and bar
be Optional[str]
, but then an instance when both are None
is type-correct, and therefore the class does not correctly represent the command line interface.
My suggestion addresses this. However, it would have to be modified so that each class will only include one option from the mutually exclusive group. This means creating a class for each command line option in the group. I think this is not a sufficiently ergonomic solution and I don't see an alternative. There would have to be another suggestion for type-correct mutually exclusive groups.
from datargs.
So when instantiating the class when
foo
is passed, what wouldbar
hold? It would have to beNone
Actually (to reproduce the original behaviour) bar
would hold it's default value in this situation (when only foo
is chosen to be passed).
But, you're right: when instantiating the dataclass (at the end of the process) both values would be present. And the parsing process would raise an error when the 2 options is present in the command line. So the problem still stands.
Maybe the argsclass
decorator could change the way the class is instantiated (when there is a mutually_exclusive_group
parameter), but we will have to think more about it.
from datargs.
Hi @roee30
I thought a little about this:
But, you're right: when instantiating the dataclass (at the end of the process) both values would be present. And the parsing process would raise an error when the 2 options is present in the command line. So the problem still stands.
Actually, I think there is no problem in having the 2 fields in the final class instance, because argparse
will make sure that only one of the arguments in the mutually exclusive group was present on the command line, but they both may be present in the class.
Take a look on this example:
import argparse
parser = argparse.ArgumentParser(prog="PROG")
group = parser.add_mutually_exclusive_group()
group.add_argument("--foo")
group.add_argument("--bar")
args = parser.parse_args(['--foo', 'test'])
print(args)
# Output: Namespace(foo='test', bar=None)
The other not passed argument receives the value of its default. And mutually exclusive arguments must be optional.
Is that right?
from datargs.
One of my concerns is that I don't really like naming groups with a string like in your opening comment for this issue since it doesn't detect typos.
Yeah, you're right.
I know that this is not nice but... what about integers?
from datargs.
Related Issues (20)
- `attrs` based classes fail with `nargs` option. HOT 2
- Static/dynamic type consistency for optional parameters, nargs? HOT 4
- Unable to pass `action` in field.metadata HOT 1
- Optional typing with Enum class HOT 1
- datargs doesn't seem to support `from __future__ import annotations` HOT 4
- Optional sequences don't seem to be supported HOT 1
- Slight error in comparison to simple-parsing HOT 1
- PyPI release? HOT 1
- Show default value support HOT 2
- nargs is not support *, which argparse support HOT 1
- The default type is not same as the return type HOT 1
- ImportError: cannot import name 'get_origin' HOT 1
- Support add_argument type parameter HOT 1
- Union operator (`|`) introduced in python 3.10 is not supported.
- pylance (pyrigth) reporting error of returned type of `arg` function
- [Feature request] make `aliases` parameters overwrite the default field name in the command line HOT 2
- [Feature request] make `aliases` in `arg()` behaves same as in the original `add_argument()` method HOT 2
- Union operator (`|`) incompatible with __future__.annotations HOT 2
- Boolean argument handling HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from datargs.