• Python Snacks
  • Posts
  • Click vs argparse - Which CLI Package is Better?

Click vs argparse - Which CLI Package is Better?

Check out the top 2 CLI-building packages to see which one is better for your application

If you’ve ever run into a situation where you’ve had to build a command line application, you may have used either argparse or Click libraries.

Both libraries allow you to build out a command line application or integrate commands to be used on the command line in your application. Both libraries offer unique capabilities to cater to different needs.

What is argparse?

argparse is a Python library for writing user-friendly command-line interfaces. It’s included with Python’s standard library, meaning that it does not require any additional installation.

This package aims to easily write small command line applications quickly. Over click, argparse has the following advantages:

  1. Standard Library Inclusion: This is argparse’s most significant advantage: it’s included with the standard library. This reduces the number of dependencies in your project.

  2. Subparsers for Commands: The package supports subparsers, which is particularity useful for scenarios where each subcommand might have a drastically different set of parameters and behaviors.

  3. Argument Dependency Handling: Lastly, argparse provides a bit more of a straight-forward mechanism for making arguments conditional based on other arguments. For instance, if we were to create a CLI application that takes a username and password:

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

# Add a flag for login
parser.add_argument('--login', action='store_true', help='Flag to indicate login is required')

# Add an argument for password
parser.add_argument('--password', help='Password for login', required=False)

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

# Check if login is used, then make sure password is also provided
if args.login and not args.password:
    parser.error("--password is required if --login is used.")
else:
    print("Login flag:", args.login)
    if args.login:
        print("Password provided:", args.password)

Here, we’re making sure that the --password flag is passed in when --login is being used.

What is Click?

Click is a Python package for creating command-line interfaces (CLIs) in a composable way.

Click aims to make the process of writing command-line tools quick and easy by removing boilerplate code and providing a cleaner syntax compared to other CLI tools like argparse.

There’s a few advantages that Click has over argparse:

  1. Automatic Help Page Generation: Click provides an automatic help page generation that is built out more than argparse. This allows for quicker development to create user-friendly CLI applications.

  2. Built-in Support for Complex Argument Types: Click goes beyond basic string and integer types and natively supports a variety of complex data types, such as file paths, enums, and ranges.

  3. Nested Commands: While you can do this with argparse, Click supports the creation of nested commands, but is much more straight-forward and more scalable.

 

Code reviews can be difficult, but it’s my goal to help you become a better software engineer. That is why I’m taking pre-orders for the Software Engineer’s Code Review Guide, packed full of information to make code reviews easier.

This guide includes:

  • Over 30 software checks to make sure you’re pull request ready,

  • Downloadable ready-to-use pull request markdown templates,

  • Analysis on various PR’s from top open source Python packages such as matplotlib, NumPy, and Pandas.

The first 15 pre-orders will receive a 70% discount from full price with a 15 day money back guarantee! Don’t wait on this special offer - once the guide officially launches, these exclusive offers go away.

 

Comparing code of click and argparse

Let’s suppose we’re writing out a small file search utility that allows users to search for files in a directory by extension.

Our command for this would be something like:

python search_files.py /path/to/directory .txt -r

This script starts in the directory /path/to/directory and searches for all files ending in .txt.

To make the code simpler to read, the logic to iterate over the files is refactored below:

def search_files(directory, extension, recursive):
    matching_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith(extension):
                matching_files.append(os.path.join(root, file))
        if not recursive:
            break
    return matching_files

Now, if we were to write this utility using argparse, our code may look as such:

import argparse

def main():
    parser = argparse.ArgumentParser(description="Search for files by extension in a directory.")
    parser.add_argument("directory", type=str, help="The directory to search in")
    parser.add_argument("extension", type=str, help="The file extension to search for (e.g., .txt, .py)")
    parser.add_argument("-r", "--recursive", action="store_true", help="Search recursively in subdirectories")

    args = parser.parse_args()

    matching_files = search_files(args.directory, args.extension, args.recursive)

    if matching_files:
        print("Matching files:")
        for file in matching_files:
            print(file)
    else:
        print(f"No files with extension '{args.extension}' found in directory '{args.directory}'")

if __name__ == "__main__":
    main()

Now, the same implementation is used, but with Click:

import click

@click.command()
@click.argument('directory', type=click.Path(exists=True))
@click.argument('extension')
@click.option('--recursive', '-r', is_flag=True, help="Search recursively in subdirectories")
def main(directory, extension, recursive):
    """Search for files by extension in a directory."""
    matching_files = search_files(directory, extension, recursive)

    if matching_files:
        click.echo("Matching files:")
        for file in matching_files:
            click.echo(file)
    else:
        click.echo(f"No files with extension '{extension}' found in directory '{directory}'")

if __name__ == "__main__":
    main()

Which is better?

The answer to “Which is better: argparse or click?” largely depends on the scope and needs of your project. Both libraries shine in different scenarios, and the choice boils down to your specific use case, preferences, and priorities.

When to use argparse

argparse is the go-to choice if:

  • You prioritize simplicity and minimal dependencies: Since argparse is part of Python’s standard library, it doesn’t require additional installation. This makes it ideal for lightweight projects or environments where external dependencies are restricted.

  • You’re working on smaller scripts or tools: argparse’s straightforward API is perfect for small, quick-and-dirty command-line utilities where advanced features or extensive customization aren’t necessary.

  • Standard library integration is a must: For organizations or projects with strict rules about using only built-in libraries, argparse is often the default choice.

  • Subparser functionality is key: If your CLI application has multiple distinct commands (like git commit and git push), argparse’s subparser support is robust and powerful.

When to use click

click is better suited if:

  • You want a polished user experience out of the box: click generates beautifully formatted help pages and handles user input elegantly. If your CLI tool will be used by a wide audience, this can make a significant difference.

  • Your application requires scalability and maintainability: For complex projects with nested commands, reusable components, and advanced input handling, click offers a cleaner and more intuitive API.

  • You value developer productivity and clean code: click’s decorators and built-in features minimize boilerplate code, making it faster and more enjoyable to write and maintain CLI tools.

  • You need advanced argument types: If you’re working with custom data types or need to validate inputs like file paths or enums, click makes this process seamless compared to argparse.

Key Tradeoffs Table

Feature

argparse

click

Dependency

Built-in (no external libraries required)

Requires installation

Learning Curve

Easy for basic tasks

Slightly steeper but rewards investment

Help Pages

Basic formatting

Rich, detailed, and user friendly

Customization

Flexible but verbose

Streamlined and intutive

Nested Commands

Supported, but verbose to implement

Simple and scalable with decorators

Community and Ecosystem

Smaller, as it’s built in

Larger, with community extensions available

My Take

While I personally lean towards click due to its scalability, clean syntax, and modern features, that doesn’t mean it’s always the best choice for every project. For simple scripts where dependencies should be minimal, argparse is often sufficient and more appropriate. However, for more complex applications or those requiring extensive customization, Click is hard to beat.

Ultimately, both tools are excellent for building CLI applications. If you’re unsure which one to choose, start by defining your project’s requirements:

  • Are you aiming for simplicity and minimalism? Go with argparse.

  • Do you want your CLI to be scalable and user-friendly? click is your best bet.

In the end, there’s no universal “better” library - just the right one for your specific needs.

📧 Join the Python Snacks Newsletter! 🐍

Want even more Python-related content that’s useful? Here’s 3 reasons why you should subscribe the Python Snacks newsletter:

  1. Get Ahead in Python with bite-sized Python tips and tricks delivered straight to your inbox, like the one above.

  2. Exclusive Subscriber Perks: Receive a curated selection of up to 6 high-impact Python resources, tips, and exclusive insights with each email.

  3. Get Smarter with Python in under 5 minutes. Your next Python breakthrough could just an email away.

You can unsubscribe at any time.

Interested in starting a newsletter or a blog?

Do you have a wealth of knowledge and insights to share with the world? Starting your own newsletter or blog is an excellent way to establish yourself as an authority in your field, connect with a like-minded community, and open up new opportunities.

If TikTok, Twitter, Facebook, or other social media platforms were to get banned, you’d lose all your followers. This is why you should start a newsletter: you own your audience.

This article may contain affiliate links. Affiliate links come at no cost to you and support the costs of this blog. Should you purchase a product/service from an affiliate link, it will come at no additional cost to you.

FAQ: Python’s Click vs argparse

  1. What are argparse and Click in Python?

    argparse and Click are Python libraries used for building command-line interfaces (CLI). While argparse is included in Python’s standard library, Click is an external package that offers a more streamlined and scalable approach to CLI development.

  2. What are the main advantages of using argparse?

    • Standard Library Inclusion: argparse is included with Python’s standard library, meaning no additional installation is required.

    • Subparsers for Commands: argparse allows for subcommands, which is useful when different commands need different parameters.

    • Argument Dependency Handling: argparse provides mechanisms to make certain arguments conditional based on others.

  3. What are the main advantages of using Click?

    • Automatic Help Page Generation: Click automatically generates a more user-friendly help page compared to argparse.

    • Support for Complex Argument Types: Click natively supports more complex argument types such as file paths, enums, and ranges.

    • Nested Commands: Click simplifies the creation of nested commands, making it easier to scale CLI applications.

  4. When should I choose Click over argparse?

    Click is ideal when building larger, more complex CLI applications that require scalability, nested commands, and cleaner code. It’s also preferred when you need advanced features like automatic help generation and support for complex argument types.

  5. Is Click more scalable than argparse?

    Yes, Click is generally considered more scalable due to its support for nested commands and its ability to handle more complex CLI structures with ease.

  6. How does the code structure differ between Click and argparse?

    Click typically results in cleaner and more maintainable code with fewer lines of boilerplate, while argparse may require more verbose code, especially as the complexity of the CLI grows.

  7. Do I need to install Click separately?

    Yes, unlike argparse, which is part of Python’s standard library, Click needs to be installed using pip (pip install click).

  8. Can I combine Click and argparse in a single project?

    While it’s technically possible to use both libraries in the same project, it’s generally not recommended due to potential conflicts and inconsistencies. Choose one based on your project’s requirements.

  9. Which library is better for beginners: Click or argparse?

    argparse might be easier for beginners because it’s included in Python’s standard library and has straightforward usage. However, Click can be more intuitive for those who want to avoid boilerplate and prefer a cleaner syntax.

  10. How does Click handle complex argument types compared to argparse?

    Click has built-in support for more complex argument types, such as file paths and enums, making it easier to work with these data types without additional code. argparse, while flexible, often requires more manual handling for such cases.

Related Articles

  1. Mastering CLI Development in Python: A Comparison of Click and Its Competitors

  2. Plotext: Plotting in the Terminal

  3. Building User-Friendly Python Command-Line Interfaces with Click

  4. Testing argparse Applications

  5. argparse – Command line option and argument parsing.

Reply

or to participate.