Explain Codes LogoExplain Codes Logo

What is the right way to treat Python argparse.Namespace() as a dictionary?

python
namespace
argparse
dictionary
Anton ShumikhinbyAnton Shumikhin·Mar 12, 2025
TLDR

If you're in haste and just want a quick way to convert argparse.Namespace() into a dictionary, use vars(). It allows you to handle arguments like a dictionary:

import argparse # Baking a parser and adding ingredients parser = argparse.ArgumentParser() parser.add_argument('--foo', type=int) # Baking time! Seal arguments into a dictionary args = parser.parse_args() args_dict = vars(args) # Gotta taste it now! Also sure to taste good even if not identical value = args_dict.get('foo', 'default_value')

Sneaky Tip: Go with args_dict.get('key', 'default_value') to avoid KeyError, just like using a GPS to avoid getting lost on the road.

Safe Navigation through Namespace

If you are a safe rider, befriend hasattr() to check if the road ahead exists and getattr() to keep moving on the right path with Namespace:

# Safe riding with hasattr() and getattr() if hasattr(args, 'foo'): value = getattr(args, 'foo') else: value = 'default_value'

You're now a sheepdog ensuring your Namespace sheep don't go astray.

The Fairy Godmother: vars() Function

vars() is the fairy godmother that transforms any object, yes, even Cinderella's carriage like argparse.Namespace, into a charming prince of a dictionary. Totally official and standard.

Don't Trespass: __dict__Property

Although __dict__ can be conjured to access Namespace, keep off the grass. Use footpaths like vars() to keep the property clean and protected.

Before You Hallucinate Namespace into a Dict

Check if you really need to transform argparse.Namespace into a dictionary. If your method smiles at a dictionary object, you have the green light. But for other events, just play with the attributes:

# Direct attribute party foo_value = args.foo

Turn Your Namespace into a Dict, When...

... such a behavior feels appropriate. Like when a function demands a dictionary input, merging command-line arguments with other dictionary playmates is needed, or the Namespace needs a makeover for saving to a file.

Spontaneous Argument Scenarios

In a mystical land where arguments come unannounced, you can't set up all potential keys. Fret not, let vars() handle the surprise guests.

# Mysterious talents showcasing post-parsing setattr(args, 'dynamic_arg', 'value') args_dict = vars(args) # 'dynamic_arg' is now partying with others inside the dictionary

Wishing Namespace Back from Dict

If you have a dict and yearn for argparse.Namespace(), make a wish and see it come true!

new_namespace = argparse.Namespace(**your_dict)