[Tutor] ?????

Kent Johnson kent37 at tds.net
Mon May 25 15:19:50 CEST 2009


On Mon, May 25, 2009 at 8:42 AM, Christian Witts <cwitts at compuscan.co.za> wrote:
> prasad rao wrote:
>>
>> hello
>>      I get a problem while trying to print non callable
>> items in dir(module).May be as the items are strings.
>>
>> for x in dir(sys):
>> ?? if sys.x is callable:
>> ????  print sys.x()
>> ?? else:print sys.x
>>
>>
>> Traceback (most recent call last):
>>  File "<pyshell#10>", line 2, in <module>
>>    if sys.x is callable:
>> AttributeError: 'module' object has no attribute 'x'
>
> What you should be doing is rather
>
> for attrib in dir(sys):
>   if callable('sys.%s' % attrib):
>       print 'Callable: sys.%s' % attrib
>   else:
>       print 'Not Callable: sys.%s' % attrib

No; 'sys.%s' % attrib is a string, you are just asking if a string is
callable. The correct way to get an attribute whose name you have is
to use getattr():
  if callable(getattr(sys, x)):

Kent


More information about the Tutor mailing list