[파이썬] argparse Namespace 객체 이해

If you’ve ever worked with command line interfaces (CLI) in Python, you’ve probably come across the argparse module. It provides a convenient way to parse command line arguments and convert them into Python objects.

One of the core components of argparse is the Namespace object. This object is automatically created by argparse and acts as a container for the values of the command line arguments.

Creation of a Namespace Object

To create a Namespace object, you first need to define your CLI argument parser using argparse.ArgumentParser(). Once you’ve defined your parser, you can call the parse_args() method to parse the provided command line arguments and obtain a Namespace object.

Here’s an example:

import argparse

# Create argument parser
parser = argparse.ArgumentParser()
parser.add_argument('--input', help='input file')
parser.add_argument('--output', help='output file')

# Parse command line arguments
args = parser.parse_args()

# Access the values using the Namespace object
print(args.input)
print(args.output)

In the above example, we define two command line arguments: --input and --output. After parsing the command line arguments, the values are stored in the args object, which is an instance of Namespace. We can access the values using the attribute syntax (args.input and args.output in this case).

Accessing Values in a Namespace Object

As mentioned above, the values of the command line arguments can be accessed using the attribute syntax with the args object. Each command line argument is represented as an attribute in the Namespace object.

If an argument is provided on the command line, its value will be stored in the respective attribute. If an argument is not provided or has a default value, the attribute will have None assigned to it.

In case an argument is specified multiple times, the last occurrence will be the value stored in the args object.

Here’s an example to demonstrate accessing values in a Namespace object:

import argparse

# Create argument parser
parser = argparse.ArgumentParser()
parser.add_argument('--name', default='John Doe', help='name of the person')
parser.add_argument('--age', type=int, help='age of the person')

# Parse command line arguments
args = parser.parse_args()

# Access the values using the Namespace object
print(args.name)
print(args.age)

In this example, the --name argument has a default value of 'John Doe', and the --age argument expects an integer. If no value is provided for --age, its attribute in the args object will be None.

Conclusion

Understanding the Namespace object in the argparse module is essential when working with command line interfaces in Python. It allows us to access the values of command line arguments in a convenient and structured manner.