Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a namespace object?

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?

like image 282
Shashank Garg Avatar asked Dec 29 '13 17:12

Shashank Garg


People also ask

What is namespace example?

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.

How do I create a namespace object?

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.

What is use of namespace in Python?

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".

What is built in namespace in Python?

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().


3 Answers

  • The documentation for argparse.Namespace can be found here.
  • You can access the s attribute by doing args.s.
  • If you'd like to access this as a dictionary, you can do vars(args), which means you can also do vars(args)['s']
like image 61
Bill Lynch Avatar answered Oct 13 '22 09:10

Bill Lynch


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).

like image 3
Martijn Pieters Avatar answered Oct 13 '22 09:10

Martijn Pieters


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

like image 1
Veaceslav Mindru Avatar answered Oct 13 '22 08:10

Veaceslav Mindru