Search code examples
pythonpython-2.7evalbuilt-in

Check if __builtins__ is callable using list comprehension, avoiding errors with eval(print)


I would like to check if those listed in __builtins__ return True from callable (as a method for testing if they're a function or not). I'm hoping to return a list of those functions in the Python documentation. I realise additional items such as AttributeError return True for callable, that's fine.

The following returns a SyntaxError when I call it (due to eval(print)):

[callable(eval(x)) for x in dir(__builtins__)]
SyntaxError: unexpected EOF while parsing

How can I test which of those in __builtins__ are callable functions while sidestepping errors thrown from eval(print)?


Solution

  • A more robust way of doing this would be to use getattr:

    >>> [callable(getattr(__builtins__, attr)) for attr in dir(__builtins__)]
    [True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, True, True, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, True, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, False, True, True, True, True, True, True, True, True, True, True, True, False, True, False, False, True, True, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]
    >>>