Coder Social home page Coder Social logo

Comments (8)

roee30 avatar roee30 commented on August 23, 2024 1

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.

roee30 avatar roee30 commented on August 23, 2024

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.

Diogo-Rossi avatar Diogo-Rossi commented on August 23, 2024

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.

Diogo-Rossi avatar Diogo-Rossi commented on August 23, 2024

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.

roee30 avatar roee30 commented on August 23, 2024

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.

Diogo-Rossi avatar Diogo-Rossi commented on August 23, 2024

So when instantiating the class when foo is passed, what would bar hold? It would have to be None

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.

Diogo-Rossi avatar Diogo-Rossi commented on August 23, 2024

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.

Diogo-Rossi avatar Diogo-Rossi commented on August 23, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.