Skip to content

gh-114920: Make iterable and subscriptable the Namespace object in argparse lib#114926

Closed
milanbalazs wants to merge 7 commits into
python:mainfrom
milanbalazs:main
Closed

gh-114920: Make iterable and subscriptable the Namespace object in argparse lib#114926
milanbalazs wants to merge 7 commits into
python:mainfrom
milanbalazs:main

Conversation

@milanbalazs
Copy link
Copy Markdown

@milanbalazs milanbalazs commented Feb 2, 2024

With this change the Namespace will be iterable and subscriptable.

Issue reference: #114920

For example:

import argparse

parser: argparse.ArgumentParser = argparse.ArgumentParser(description=__doc__)

parser.add_argument(
    "--test_1",
    action="store_true",
)

parser.add_argument(
    "--test_2",
    type=str,
)

parser.add_argument(
    "--test_3",
    type=int,
    default=0
)

args = parser.parse_args()
for x in args:
    print(x)

Test:

>>> python3 test_2.py
{'test_1': False}
{'test_2': None}
{'test_3': 0}

>>> python3 test_2.py --test_3 5 --test_1
{'test_1': True}
{'test_2': None}
{'test_3': 5}

Without my change the same behavior can be done only with tricky and ugly solutions, like:

args = parser.parse_args()

for x in vars(args):
    print({x: getattr(args, x)})

Furthermore, with the __getitem__ method implementation, the Namespace object is subscriptable, so it's possible to get the value directly from the object, like:

args = parser.parse_args()

print(args["test_1"])

@encukou
Copy link
Copy Markdown
Member

encukou commented Apr 15, 2024

The issue was closed, so I'll close the pull request as well.

@encukou encukou closed this Apr 15, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants