iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🥔

From a simple query about argparse to a deep dive into Python's design philosophy

に公開

Table of Contents

Background and Conclusion
What was that opening code actually doing?
What is argparse anyway?
Key argparse methods and their roles
What is vars(args)?
Why is vars a built-in function?
What is happening behind vars?
Specifications of Dynamic Languages
Side note: How vars(args) is used in production
Closing Thoughts

Background and Conclusion

app.py
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--env", required=True, type=str)
    parser.add_argument(...)

    args = parser.parse_args()
    run_flows(args)

This is the main function of a batch process that runs every month.

Even though it's just this code, it manages processes running for about 20 hours. Furthermore, the process flow branches differently between production and test environments.

That's when I had a sudden question:

  • run_flows manages the main process, but it only receives args.
  • The main function has no arguments.
  • Yet, "environment variables" and "execution conditions" are being used somewhere.

"Where are these arguments being passed from?" Starting from this small question, I did some research and found out:

  • argparse is a library used to create CLI tools.
  • argparse.parse_args() is used to pass command-line arguments.
  • argparse.parse_args() returns an object of the NameSpace type.
  • Its contents can be extracted as a dictionary using vars(args).
  • The core of this is the special attribute __dict__, common to all Python objects.

This is a story of how a small question unexpectedly led to uncovering the very object design of Python as a dynamic language.

This article summarizes the flow of that learning process. I will cover the following topics:

  • How to create command-line tools in Python
  • How to incorporate command-line arguments into a script
  • How Python objects store their attributes
  • Common object design patterns in dynamic languages

I won't just stop at how to use argparse; I will delve into "why it is designed this way."

What was that opening code actually doing?

I have reiterated the opening code below.

app.py
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--env", required=True, type=str)
    parser.add_argument(...)

    args = parser.parse_args()
    run_flows(args)

In summary, this code "converts command-line arguments into a Python object and passes that object to the entry point of the process."

It uses the argparse library to perform this conversion into a Python object.

What is argparse anyway?

argparse is a standard Python library used to define and parse command-line arguments, converting them into a format that is easy to handle within a program.

Since it might be hard to visualize with just words, here is a concrete example.

argparse_exe.py
# Example of a command to enter on the command line
python app.py --env prod --date 2025-01-01

# Inside argparse, attributes are defined as follows
args.env # == "prod"
args.date # == "2025-01-01"

In this way, argparse is a library that converts variables entered via the command line so they can be processed within your script. As a result, it could be said that argparse is also a library for building command-line tools.

Command-line tools are programs that you execute by providing arguments from a command line like bash, and which exchange processing results via standard input and standard output.

In short, while you usually write and run Python scripts, argparse is what allows those scripts to be executed from the command line.

Primary methods of argparse and their roles

ArgumentParser()

parser = argparse.ArgumentParser()
  • Role
    • Generates an object to manage the specifications for command-line arguments.
    • Serves as the foundation for subsequent add_argument and parse_args calls.

add_argument()

parser.add_argument("--env", required=True, type=str)
  • Role
    • Defines the rules for arguments to be received.
      • It only declares the specification.
      • No value exists yet at this stage.

parse_args()

args = parser.parse_args()
  • Role
    • Actually accepts command-line arguments.
    • Parses them according to the rules defined by add_argument.
    • Returns the result as a Namespace object.
  • What happens behind the scenes
    • Accepts simple strings from the command line and converts them to the specified types.
    • Performs validation for required arguments.
    • Detects invalid arguments.
    • Displays help messages.

Using the primary methods above, command-line arguments are converted into a Python object.

In the opening code, parse_args() is assigned to an argument called args, but as mentioned, the return value is a special type called Namespace.

When you check the contents, you will see something like Namespace(env="prod", date="2025-01-01", ...), where the command-line arguments are aggregated into args.

While you can extract individual argument values by specifying them like args.env, you may need to convert them to a more Python-friendly type for reasons such as:

  • The number of command-line arguments might be unknown.
  • A more loosely coupled design can be achieved by not depending on the special Namespace type.
  • You want to simplify debugging and visualization.

The method for doing this is vars(args), which is described next.

What is vars(args)?

vars is a built-in function used to extract the attributes an object holds internally as a dictionary.

In this case, the image is as follows:

# [Image] args holds data as a Namespace type
args = Namespace(env="prod", date="2025-01-01", ...)

# Convert to dict type using vars
dict_args = vars(args)
dict_args = {
    "env": "prod",
    "date": "2025-01-01",
    ...
    }

By converting to a dictionary type in this way, you can handle command-line arguments collectively as a "collection of names and values."

One thing that piques my interest here is: Why is vars a built-in function instead of a method of argparse?

This answer is the most interesting part of this investigation. The fact that it is a built-in function means that it utilizes behavior common to Python objects.

By digging into this, we can see the specifications of Python and other dynamic languages.

Why is vars a built-in function?

vars is a built-in function because the processing used to convert from Namespace to dictionary type is not a process specific to argparse, but utilizes a mechanism common to all Python objects.

To be more precise, vars is provided as a function that serves as a common interface for extracting attributes as a dictionary from any "Python object that possesses attributes."

It is important to note the following facts:

  • vars does not know about argparse.
  • It does not treat the Namespace type specially.

In other words, the reason vars(args) works is not because args is an argparse object, but because it possesses attributes as a Python object.

What is happening behind the scenes of vars?

Actually, the process vars(args) is the same as args.__dict__; in fact, the former is a function that calls the latter.

...That might be a bit confusing, so let me explain step by step.

In Python, many objects internally hold a dictionary called __dict__, which maintains the mapping between attribute names and their values.

This is because Python classes ultimately inherit from the object class and adopt a design where "attributes are managed as a dictionary."

Therefore, __dict__ exists not only in argparse but also in your own custom classes as shown below:

class Config:
    def __init__(self):
        self.env = "prod"
        self.date = "2025-01-01"

config = Config()
print(vars(config)) # {"env": "prod", "date": "2025-01-01"}
print(config.__dict__) # {"env": "prod", "date": "2025-01-01"}

print(vars(config) is config.__dict__) # True

From this, we can understand:

  • vars(obj) returns obj.__dict__ as it is.
  • __dict__ is a dictionary used by Python objects to hold attributes.

So, why does Python adopt such a design?

Specifications of Dynamic Languages

Python is a dynamic language, allowing you to freely add or change attributes on an object at runtime.

config = Config()
config.env = "prod"
config.new_param = 123

To make such operations possible, one must accept the following premises:

  • Attribute names are not fixed in advance.
  • Attributes increase or decrease at runtime.

To satisfy these requirements, Python adopts a design where "attributes = mappings between names and values" are managed as a dictionary (dict).

In Python, dict (hash map) is the fundamental data structure used to handle key-value pairs flexibly and efficiently. For more on hash maps, please see the following article:
https://zenn.dev/zenn_mita/articles/f9811270b871d5

Therefore,

  • Object attributes
  • CLI arguments
  • Configuration information

These "collections of named data" are naturally expressed as dictionaries. obj.__dict__ is the standard storage location for this purpose.

Returning to the point, the Namespace object returned by argparse is simply an object that follows this Python design philosophy.

It is simply taking "collections of names and values" (command-line arguments) and mapping them into a form that Python can handle easily by default (attributes + dictionary).

Aside: How vars(args) is used in the field

In practice, it is often used for unpacking, allowing command-line arguments to be passed to a function all at once.

args = ArgsDataClass(**vars(args), ...)

Unpacking is a syntax that expands the keys and values of a dictionary directly into keyword arguments. If a dictionary like {"env": "prod", "date": "2025-01-01"} is passed, it expands into an argument list like ArgsDataClass(env="prod", date="2025-01-01", ...).

This approach offers several benefits:

  • Command-line arguments can be converted directly into data classes.
  • Values can be passed without depending on argparse.Namespace.
  • Argument definitions can be explicitly typed as classes.

In particular, argparse handles only the acquisition of execution conditions, and subsequent logic can be built using data classes or dictionaries, enabling a cleaner design with separated responsibilities.

As such, vars(args) is not only a means to check CLI arguments but is also frequently used in professional development as a "bridge" to convert them into standard Python data structures.

Thoughts

This explanation is way too loooooooong!!!!
I just wanted to check how to pass arguments...

  1. I didn't understand the flow of arguments.
  2. I looked it up, but I didn't understand the meaning of the commands being run on the command line.
  3. I figured out that argparse was handling them, but I didn't understand the specific process flow.
  4. I understood that args.○○ was being used for various things, but I didn't know what was happening behind the scenes.
  5. I found vars(args) being used for unpacking, but I didn't understand why unpacking was possible.
  6. I understood that __dict__ held attributes, but I didn't see the connection to argparse.
  7. I learned that all objects with Python attributes inherit from a CPython class called object, which holds the __dict__.
  8. I learned that this design is the same not only in Python but also in other dynamic languages like JavaScript.
  9. I didn't know what I was researching anymore, so I decided to summarize it.
  10. Wrote the article.

That was the flow.
Just like digging for potatoes in kindergarten, I felt that the more I dug, the more new, massive pieces of knowledge appeared.

I learned that even an unexpected, tiny question can lead to knowledge connected to the entirety of programming, so I plan to keep digging.

Discussion