[파이썬] argparse 사용자 정의 타입 및 검증

Command-line argument parsing is a common task in Python programming. The argparse module provides a simple and efficient way to handle command-line arguments. While argparse supports various built-in data types for argument validation, there may be cases where you need to define custom types and perform additional validation.

In this blog post, we will explore how to define custom types and perform validation using the argparse module in Python.

Defining Custom Types

To define a custom type, we need to create a class that represents the desired type. This class should include a __call__ method, which is responsible for converting the input string into the desired type. Let’s consider an example where we want to define a custom type for parsing and validating email addresses.

import argparse

class EmailType:
    def __call__(self, value):
        # Perform email validation logic here
        if not "@" in value:
            raise argparse.ArgumentTypeError(f"{value} is not a valid email address")
        return value

# Create the argument parser
parser = argparse.ArgumentParser()

# Add an argument with custom type
parser.add_argument("--email", type=EmailType())

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

# Access the email argument
print(args.email)

In the above code snippet, we define a EmailType class that represents our custom type. The __call__ method performs the email validation logic. If the input string does not contain the “@” character, it raises an argparse.ArgumentTypeError. Otherwise, it returns the email address.

Performing Validation

Besides defining custom types, we often need to perform additional validation on the input values to ensure they meet certain criteria. With argparse, we can achieve this by utilizing the add_argument() method’s choices, required, and validators parameters.

Let’s consider an example where we want to ensure that the argument value is a positive integer. We can achieve this by using the type, choices, and required parameters of the add_argument() method.

import argparse

def positive_int(value):
    # Perform positive integer validation logic here
    ivalue = int(value)
    if ivalue <= 0:
        raise argparse.ArgumentTypeError(f"{value} is not a positive integer")
    return ivalue

# Create the argument parser
parser = argparse.ArgumentParser()

# Add an argument with validation
parser.add_argument("--count", type=positive_int, required=True)

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

# Access the count argument
print(args.count)

In the above code snippet, we define a positive_int function that performs the positive integer validation logic. If the input value is not a positive integer, it raises an argparse.ArgumentTypeError. Otherwise, it returns the validated integer value.

We then use the type parameter of the add_argument() method to specify the custom validation function.

By using the choices parameter, we can restrict the allowed values to a predefined set. This is useful when you have a limited set of acceptable options for an argument.

Conclusion

In this blog post, we explored how to define custom types and perform validation using the argparse module in Python. We saw that by creating a class with a __call__ method, we can define our own custom types for command-line arguments. We also learned how to perform additional validation using custom validation functions and the choices parameter.

By leveraging these techniques, you can handle command-line arguments more effectively and ensure that the input values meet your requirements.

Remember to follow best practices and provide meaningful error messages when performing validation to make your command-line interfaces more user-friendly and robust.