[PYTHON] How to specify an infinite number of tolerances in the numeric argument validation check of argparse

There is a standard library called argparse that supports the argument-related processing of Python scripts. With argparse, you can add valid arguments, including validation checks. This time, I will describe how to specify the argument of "there is a valid range of numerical values" with argparse.

Overview of argparse

argparse is a Python library that parses command line options and arguments. It is available from Python 2.7 and is included as a standard library (so you don't have to bother to use pip and you don't have to add "please put this library" when distributing it to other users).

Official Python documentation argparse https://docs.python.jp/3/library/argparse.html

In addition to argparse, there are the following Python libraries that perform this kind of analysis.

Option parser that Pythonista knows http://qiita.com/petitviolet/items/aad73a24f41315f78ee4

Check the tolerance

To include the argument analysis process using argparse, implement as follows. (The following adds the integer value option "-s".)

Argument check sample.py


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='LightsOut Solver')
    parser.add_argument('-s', type=int, help='LightsOut Size')

ʻIf you specify string or int in the argument type of ArgumentParser # add_argument`, it will check whether the value specified as the argument can be treated as that type.

In order to specify "tolerance range" as a condition for adding arguments as described above, it is OK to enter a value indicating the tolerance range in the argument choice of ʻArgumentParser # add_argument`.

Argument check sample2.py


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='LightsOut Solver')
    parser.add_argument('-s', type=int, choice=range(1,6), help='LightsOut Size')

However, you can specify a solid value for this choice only if it can be represented by an array. In other words, only a finite number of ranges can be narrowed down. To specify an infinite number of ranges (for example, "integer of 2 or more" or "real number of 0 or more and 1 or less"), "function to judge whether it is an acceptable value" instead of "array that specifies the range" It is OK if you specify. Below is a sample code that specifies an integer greater than or equal to 2 as a range.

Argument check sample3.py


class range_check(object):
    def __init__(self, low_limit=None, high_limit=None, vtype="integer"):
        self.min = low_limit
        self.max = high_limit
        self.type = vtype

    def __contains__(self, val):
        ret = True
        if self.min is not None:
            ret = ret and (val >= self.min)
        if self.max is not None:
            ret = ret and (val <= self.max)
        return ret

    def __iter__(self):
        low = self.min
        if low is None:
            low = "-inf"
        high = self.max
        if high is None:
            high = "+inf"
        L1 = self.type
        L2 = " {} <= x <= {}".format(low, high)
        return iter((L1, L2))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='LightsOut Solver')
    parser.add_argument('-s', type=int, choices=range_check(low_limit=2), help='LightsOut Size')

In addition, how to describe the sample project built using this code. https://github.com/LyricalMaestro/lightsout-solver-python

Summary

If you make full use of the check method, you can use argparse to perform validation check with a high degree of freedom. Use it to create great scripts.

References

Official Python documentation argparse https://docs.python.jp/3/library/argparse.html

Option parser that Pythonista knows http://qiita.com/petitviolet/items/aad73a24f41315f78ee4

Recommended Posts

How to specify an infinite number of tolerances in the numeric argument validation check of argparse
How to get the number of digits in Python
How to find the optimal number of clusters in k-means
How to know the internal structure of an object in Python
How to check the memory size of a variable in Python
[TensorFlow 2] How to check the contents of Tensor in graph mode
How to check the version of Django
[LPIC 101] How to specify the disk partition number in the GRUB configuration file
How to mention a user group in slack notification, how to check the id of the user group
How to count the number of elements in Django and output to a template
How to know the port number of the xinetd service
[Golang] Specify an array in the value of map
[Python] Summary of how to specify the color of the figure
[Selenium] How to specify the relative path of chromedriver?
How to identify the element with the smallest number of characters in a Python list?
How to check in Python if one of the elements of a list is in another list
How to count the number of occurrences of each element in the list in Python with weight
[python] How to check if the Key exists in the dictionary
[For beginners] I want to explain the number of learning times in an easy-to-understand manner.
How to manipulate the DOM in an iframe with Selenium
How to check if the contents of the dictionary are the same in Python by hash value
How to check if a value exists in an enum
How to calculate the sum or average of time series csv data in an instant
How to increase the number of machine learning dataset images
How to get an overview of your data in Pandas
Let's see how to count the number of elements in an array in some languages [Go, JavaScript, PHP, Python, Ruby, Swift]
How to get rid of the "Tags must be an array of hashes." Error in the qiita api
How to intentionally issue an error in the shell During testing
How to handle multiple versions of CUDA in the same environment
How to determine the existence of a selenium element in Python
How to implement Java code in the background of RedHat (LinuxONE)
[Note] Items to check when an infinite loop occurs in pyenv
How to get the vertex coordinates of a feature in ArcPy
The first artificial intelligence. How to check the version of Tensorflow installed.
[Beginner memo] How to specify the library reading path in Python
[Question] In sk-learn random forest regression, an error occurs when the number of parallels is set to -1.
Check the number of prime numbers less than or equal to n
[Python] How to specify the window display position and size of matplotlib
How to check local GAE from iPhone browser in the same LAN
How to find out the number of CPUs without using the sar command
How to specify a .ui file in the dialog / widget GUI in PySide
[Python] How to put any number of standard inputs in a list
Check the in-memory bytes of a floating point number float in Python
How to compare if the contents of the objects in scipy.sparse.csr_matrix are the same
How to put a line number at the beginning of a CSV file
I want to leave an arbitrary command in the command history of Shell
I made a program to check the size of a file in Python
How to play a video while watching the number of frames (Mac)
An example of the answer to the reference question of the study session. In python.
Check the behavior of destructor in Python
The story of an error in PyOCR
Part 1 I wrote an example of the answer to the reference problem of how to write offline in real time in Python
How to check opencv version in python
How to save the feature point information of an image in a file and use it for matching
Is the number equivalent to an integer?
How to specify non-check target in Flake8
How to pass the execution result of a shell command in a list in Python
plot the coordinates of the processing (python) list and specify the number of times in draw ()
Set the number of elements in a NumPy one-dimensional array to a power of 2 (0 padded)
How to uniquely identify the source of access in the Django Generic Class View
Set an upper limit on the number of recursive function iterations in Python