-2

When I print the object I get: {'ip': 'ip', 'ip1': 'hi'}

But if I try to print the length of that I get:

Traceback (most recent call last):
    print len(options)
AttributeError: Values instance has no attribute '__len__'

I just need to know how many items are in that object (which appears to just be a dictionary).

Here is the whole code:

#!/usr/bin/python

from inspect import getmembers
from optparse import OptionParser



parser = OptionParser()
parser.add_option('-a', '--allow',
    action="store", dest="ip",
    help="query string", default="spam")

parser.add_option('-d', '--deny',
    action="store", dest="ip1",
    help="query string", default="spam")


options, args = parser.parse_args()

print 'Query string:', options.ip
print 'Query string:', options.ip1

count=0
for i in options:
  count+=1
print count

if 1:
  print "Max number of options 1"
  exit
Robert and Mike
  • 41
  • 1
  • 1
  • 2

1 Answers1

1

options is not a dictionary. It is a Values object which is one of the components of the return value of the parse_args() method.

In your code sample above, note how you use options.ip instead of options['ip']. What look like dict keys are thus being stored as instance variables of the object options. As such, they can be retrieved as a dictionary using the vars() function:

d = vars(options)
print len(d)

If you look at the source, you'll see that the Values class doesn't implement __len__ but it does implemement __str__:

def __str__(self):
    return str(self.__dict__)

(lines 843-844 in the linked-to source)

That is what you see when you use print options, and __dict__ is what is returned by the vars() function.

John Coleman
  • 51,337
  • 7
  • 54
  • 119