import argparse
parser = argparse.ArgumentParser(description='sort given numbers')
parser.add_argument('-s', nargs = '+', type = int)
args = parser.parse_args()
print(args)
On command line when I run the command
python3 file_name.py -s 9 8 76
It prints
Namespace(s=[9, 8, 76])
.
How can I access the list [9, 8, 76]? What is the namespace object. Where can I learn more about it?
Prominent examples for namespaces include file systems, which assign names to files. Some programming languages organize their variables and subroutines in namespaces. Computer networks and distributed systems assign names to resources, such as computers, printers, websites, and remote files.
So if you want to create a namespace, you just need to call a function, instantiate an object, import a module or import a package. For example, we can create a class called Namespace and when you create an object of that class, you're basically creating a namespace.
Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context".
A built-in namespace contains the names of built-in functions and objects. It is created while starting the python interpreter, exists as long as the interpreter runs, and is destroyed when we close the interpreter. It contains the names of built-in data types,exceptions and functions like print() and input().
argparse.Namespace
can be found here.s
attribute by doing args.s
.vars(args)
, which means you can also do vars(args)['s']
It is the result object that argparse
returns; the items named are attributes:
print(args.s)
This is a very simple object, deliberately so. Your parsed arguments are attributes on this object (with the name determined by the long option, or if set, the dest
argument).
you can access as args.s
, "NameSpace class is deliberately simple, just an object subclass with a readable string representation. If you prefer to have dict-like view of the attributes, you can use the standard Python idiom, vars()." Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With