boson boson - 1 year ago 92
Python Question

Choosing default argument values in python?

This code keeps giving me the error:

TypeError: 'NoneType' object has no attribute 'getitem'

class d_exposure(object):
def __init__(self):
self.files = glob.glob('C:\files')
def exposure(self,level):
level = inspect.getargspec(d_exposure().exposure)[3][0]
print level
def main():
mp = d_exposure()
mp.exposure(level = 'MID')

It seems that the problem is that it wants a default value for level. However, the traceback shows it is getting a value.

Traceback (most recent call last):
File "C:\Users\Documents\my_scripts\", line 58, in <module>
File "C:\Users\Documents\my_scripts\", line 54, in main
mp.exposure(level = 'MID')
File "C:\Users\Documents\my_scripts\", line 17, in exposure
level = inspect.getargspec(d_exposure().exposure)[3][0]

When I try giving it a default value 'DIM', then the output has 'DIM', even though the call I made was mp.exposure(level = 'MID'). Can someone please help me figure out what I'm doing wrong?

Answer Source

This line gives you the following output:

ArgSpec(args=['self', 'level'], varargs=None, keywords=None,           defaults=None)

The last entry in that is None, on which you are trying to call the getitem method by accessing the 0th element. When you give default as 'DIM', the last value in the output of getargspec method is ['DIM'] and hence it gives you 'DIM' as the answer.

When you do this in the main method:

mp.exposure(level = 'MID')

you are giving MID as the parameter and not the default value. Default value can only be given during the function definition. You haven't stated clearly what exactly you want to do instead, so I can't give you input on that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download