Hi

My "callable" function doesn't work. Who knows why?

>>> callable(print)
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    callable(print)
NameError: name 'callable' is not defined
>>>

Regards,

Mark

What version of python are you using? Did it work before and stop or just never work at all? Are any other built-in functions working?

As a replacement you could use this:

def callable_(obj):
    if "__call()__" in dir(obj):
        return True
    else:
        return False

That should provide the same functionality

Dont think you can call print,have you done that before?

In Python a callable is an object which type has a __call__ method:

def test():
    print 'hi'

>>> dir(test)
['__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__doc__', '__format__', '__get__', '__getattribute__', '__globals__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name']

>>> callable(test)
True

>>> a = 5
>>> dir(a)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__format__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'conjugate', 'denominator', 'imag', 'numerator', 'real']

>>> callable(a)
False
>>>

I'm using version 3.1 which I recently installed. I'm just starting to learn Python so this is the first time I have tried to use the function and it doesn't work. Thanks for the code suggestion, but I'm more concerned about why it doesn't work when it is supposed to be a built-in function. I'm trying to learn from a book, but I can't get the examples to work. Some built-in functions (e.g. abs()) do work.

Snippsat, as far as I understand, callable(print) should return "False" because print is not callable.

Does anyone know what module callable is defined in and how this module is loaded? Maybe abs() is in a different module. Maybe my installation is missing something in the set-up.

Read the docs of Python3:
http://docs.python.org/3.1/whatsnew/3.0.html?highlight=callable

Removed callable(). Instead of callable(f) you can use hasattr(f, '__call__'). The operator.isCallable() function is also gone.

You can run this program to check what you have available:

# print all builtin functions/methods

# do a case insensitive sort then print ...
print( '\n'.join(sorted(dir(__builtins__), key=str.lower)) )

# or send to a file ...
fout = open('Builtins.txt', 'w')
print( '\n'.join(sorted(dir(__builtins__), key=str.lower)), file=fout)

"""my result with Python 3.1 -->
__build_class__
__debug__
__doc__
__import__
__name__
__package__
abs
all
any
ArithmeticError
ascii
AssertionError
AttributeError
BaseException
bin
bool
BufferError
bytearray
bytes
BytesWarning
chr
classmethod
compile
complex
copyright
credits
delattr
DeprecationWarning
dict
dir
divmod
Ellipsis
enumerate
EnvironmentError
EOFError
eval
Exception
exec
exit
False
filter
float
FloatingPointError
format
frozenset
FutureWarning
GeneratorExit
getattr
globals
hasattr
hash
help
hex
id
ImportError
ImportWarning
IndentationError
IndexError
input
int
IOError
isinstance
issubclass
iter
KeyboardInterrupt
KeyError
len
license
list
locals
LookupError
map
max
MemoryError
memoryview
min
NameError
next
None
NotImplemented
NotImplementedError
object
oct
open
ord
OSError
OverflowError
PendingDeprecationWarning
pow
print
property
quit
range
ReferenceError
repr
reversed
round
RuntimeError
RuntimeWarning
set
setattr
slice
sorted
staticmethod
StopIteration
str
sum
super
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
True
tuple
type
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
vars
Warning
ZeroDivisionError
zip
"""

Well that explains it then!

Thanks. :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.