问题
I'm trying to put together a canonical example of how to get a list of all the builtin functions in Python. The documentation is good, but I want to demonstrate it with a provable approach.
Here, I'm essentially defining the built-in functions as the members of the default namespace that are usable and consistent with the stylistic characteristics of a function that is intended for use in a module, that is: they provide some useful functionality and begin with a lowercase letter of the alphabet.
The upside of what I'm doing here is that I'm demonstrating the filter part of list comprehensions, but it seems a bit of a dirty hack and like there should be a more straight-forward way of doing this. Here's what I'm doing so far:
import string
alc = string.ascii_lowercase
bif = [i for i in dir(__builtins__) if
any(i.startswith(j) for j in alc)]
Which gives me:
['abs', 'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
I believe that they are all callable, as with this:
bi2 = [i for i in dir(__builtins__) if
any(i.startswith(j) for j in alc)
and callable(getattr(__builtins__, i, None))]
set(bif).symmetric_difference(bi2)
I get:
set([])
So is there a better way to list the builtin Python functions? Google and stackoverflow searches have failed me so far.
I am looking for a demonstrable and repeatable method for experimental instruction. Thanks!
回答1:
import __builtin__
import inspect
[name for name, function in sorted(vars(__builtin__).items())
if inspect.isbuiltin(function) or inspect.isfunction(function)]
There's also the list in the documentation.
来源:https://stackoverflow.com/questions/20651249/how-do-i-get-a-list-of-all-the-built-in-functions-in-python