Convert Python argparse.Namespace to a dict with vars()
Codemia Knowledge Hub ·
Use vars(args). It returns the namespace's __dict__, which is the documented way to view an argparse.Namespace as a dictionary. The result is the namespace's actual storage, not a copy, so changing one changes the other; use dict(vars(args)) when you need an independent copy.
Basic conversion with vars()
vars() returns a live reference
The dictionary from vars(args) is the same object as args.__dict__, so changes flow both ways:
Why vars() instead of __dict__
Both return the same object, but vars() is the idiomatic, documented choice:
Common uses
Passing arguments to a function as kwargs
If the function has fixed parameters, any extra argparse argument raises TypeError: unexpected keyword argument. A function that accepts **kwargs takes them all.
Merging with default configuration
Serializing to JSON
vars(args) may contain values json.dumps cannot handle, such as pathlib.Path or file objects from type=argparse.FileType. Convert those before serializing.
Filtering arguments
Converting a dict back to a Namespace
Subparsers
Checking whether an argument was provided
argparse uses None as the default for optional arguments, so None cannot tell you whether the user passed the flag. To distinguish "not provided" from a real value, use a sentinel default such as argparse.SUPPRESS or a custom default object.
Two Namespace objects with the same attributes compare equal with ==. Converting to dicts and comparing is safer when attributes might have been added dynamically.
Related reading
- What is the safe way to fill multidimensional array using stdfill?
- What is the significance of load factor in HashMap?
- What is the significance of the semi clustering formula in the Google Pregel paper?
- What is the Simplest Way to Reverse an ArrayList?
- What is the sequence of SessionRunHook's member function to be called?
- What is the source code of the this module doing?
- What is the state of the art in computer chess tree searching?
- What is the syntax to insert one list into another list in python?
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.