Skip to content

Commit 7fd2f44

Browse files
Update argparse.md
1 parent 565191e commit 7fd2f44

File tree

1 file changed

+36
-1
lines changed

1 file changed

+36
-1
lines changed

recipes/python/argument-parsing/argparse.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ import argparse
7070

7171

7272
parser = argparse.ArgumentParser(description="Tool Manager")
73-
subparsers = parser.add_subparsers(dest="command", help="Available commands")
73+
subparsers = parser.add_subparsers(dest="subcommand", help="Available commands")
7474

7575
greet_parser = subparsers.add_parser("greet", help="Say hello")
7676
greet_parser.add_argument("--name", default="User")
@@ -83,6 +83,41 @@ calc_parser.add_argument("y", type=int)
8383
args = parser.parse_args()
8484
```
8585

86+
Then use basic if-else approach:
87+
88+
```python
89+
if args.subcommand == "greet":
90+
print(f"Hello, {args.name}!")
91+
elif args.subcommand == "calc":
92+
result = args.x + args.y
93+
print(f"Result: {result}")
94+
else:
95+
parser.print_help()
96+
```
97+
98+
Or function mapping for cleaner, automated, and scalable approach:
99+
100+
```python
101+
# 1. Define the logic in functions
102+
def handle_greet(args):
103+
print(f"Hello, {args.name}!")
104+
105+
def handle_calc(args):
106+
print(f"Result: {args.x + args.y}")
107+
108+
# 2. Map the functions to the parsers
109+
greet_parser.set_defaults(func=handle_greet)
110+
calc_parser.set_defaults(func=handle_calc)
111+
112+
# 3. Parse and execute
113+
args = parser.parse_args()
114+
115+
if hasattr(args, "func"):
116+
args.func(args)
117+
else:
118+
parser.print_help()
119+
```
120+
86121
Sample usage:
87122

88123
```sh

0 commit comments

Comments
 (0)