How to set several required arguments into an optional group?

Hello:

I’m trying to use the argparse module to provide the argument parsing.

In my use case, I have eight positional arguments: arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8:

  • arg1 and arg2 are required.
  • arg3 and arg4 are a couple and optional. But if users pass in one(arg3 or arg4), they must pass in the other at the same time.
  • arg5 and arg6 are another couple and same with arg3 and arg4.
  • arg7 and arg8 are another couple and same with arg5 and arg6. But they are mutually exclusive with the group arg5 and arg6

So my code is:

parser = argparse.ArgumentParser(description='Test.')
parser.add_argument('--arg1', type=str, required=True)
parser.add_argument('--arg2', type=str, required=True)
group1 = parser.add_argument_group(title='Group of arg3 and arg4')
group1.add_argument('--arg3', required=True)
group1.add_argument('--arg4', required=True)
group2 = parser.add_argument_group(title='Group of arg5 and arg6')  # group2 is not mutually exclusive with group1
group2.add_argument('--arg5', required=True)
group2.add_argument('--arg6', required=True)
group3 = parser.add_argument_group(title='Group of arg7 and arg8')  # group3 is mutually exclusive with group2
group3.add_argument('--arg7', required=True)
group3.add_argument('--arg8', required=True)

Three groups are optional which means users could just pass in --arg1 xx --arg2 xx.

But the use case: --arg1 xx --arg2 xx --arg3 xx is not allowed

I know the add_argument_group() is just used for the help message.

Is there any way to implement the example using the argparse itself instead of adding additional if-else logic?

Wow, that’s a complex and intricate logic exercise!

This looks like a strong case for a deep dive and thorough expedition through the argparse documentation. Have you studied the docs?

What do you mean by this? argparse is a standard library module.

1 Like

My understanding is that groups of arguments that necessitate each other is not currently possible without additional logic. See Add "necessarily inclusive" groups to argparse · Issue #55797 · python/cpython · GitHub.

1 Like

My mistake. I thought it was a 3rd Party library. I redacted the statement. You can delete the query of my original post, Jean.

Yes, I have reviewed the entire document, and it seems that I can only add additional judgment logic myself to implement this example.

Never mind :grinning: