Wizard
Wizard

Reputation: 22093

Retrieve the 68 built-in functions directly in python?

Command dir(__builtins__) just list all the 151 builtin libraries.

len(dir(__builtins__)) # output 151

However, It lists 68 built-in functions in 2. Built-in Functions — Python 3.6.2 documentation

I tried to get the functions from dir(__builtins__) as the following steps:

#I hardtyped the functions as comparition.
officical_builtin_functions = ['abs','all',....]
y = official_builtin_functions
len(y) #output:68
# get official builtin functions from python_builtin_library
dir(__builtins__).index('abs') #output:79
qualified_functions = python_builtin_library[79:]
qualified_functions.pop('exit')
qualified_functions.pop('credits')
qualified_functions.pop('copyright')
qualified_functions.pop('quit')
qualified_functions.pop('license')
quilified_functions.append('__import__')
# then get the 68 qualified_functions from dir(__builtins__)

How to list the 68 built-in functions directly?

Upvotes: 5

Views: 565

Answers (4)

cdlane
cdlane

Reputation: 41872

I tried to filter it (mostly) by functionality and came up with:

from inspect import isclass

documented_builtins = [x
    for x in dir(__builtins__) if not x.startswith('__') and (
        lambda y: callable(y) and not(isclass(y) and issubclass(y,
            BaseException)))(eval(x))
]

print(documented_builtins)

It produces the same 72 items that @OferSadan's simple i[0].islower() filter produces! (+1)

Additions are: copyright, credits, exit, license and quit

Deletions are: __import__

If you eliminate the not x.startswith('__') test, you get back __import__ but you also get __build_class__ and __loader__

Upvotes: 1

One approach in Python 3.5 would be to list objects that have the __module__ attribute and it set to builtins and lowercase name:

>>> sorted(k for k, v in vars(__builtins__).items()
           if k.islower() and getattr(v, '__module__', '') == 'builtins')
['__build_class__', '__import__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray',
 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'delattr', 'dict', 'dir', 
 'divmod', 'enumerate', 'eval', 'exec', 'filter', 'float', 'format', 'frozenset', 'getattr', 
 'globals', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
 'iter', 'len', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct',
 'ord', 'pow', 'print', 'property', 'range', 'repr', 'reversed', 'round', 'set', 'setattr',
 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

Notice that __import__ is listed in the docs but __build_class__ is not. 67 names on Python 3.5. The list in the docs has 68 names... This is also because help and open from the documentation do not match my filter, as open is from module io and help is from site builtins; actually the documentation is wrong, because help need not be available:

% python3 -S
Python 3.5.3 (default, Jan 19 2017, 14:11:04) 
[GCC 6.3.0 20170118] on linux
>>> help
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'help' is not defined

Likewise many exception types are always available, even though they're not listed there.

Upvotes: 4

DYZ
DYZ

Reputation: 57033

Technically, there are only 42 (in 3.4) or so builtin functions and methods in Python. The rest of the list is builtin variables and typess:

real_builtins = [e for e in dir(__builtins__) if isinstance(eval(e), type(vars))]
len(real_builtins)
# 42
real_builtins[:5] + real_builtins[-5:]
# ['__build_class__', '__import__', 'abs', 'all', 'any',
#  'round', 'setattr', 'sorted', 'sum', 'vars']
type(abs)
#<class 'builtin_function_or_method'>

Note that zip or int, for example, are not really functions. They are constructors of the namesake builtin data types:

type(zip)
# <class 'type'>
type(int)
# <class 'int'>

Upvotes: 2

Ofer Sadan
Ofer Sadan

Reputation: 11932

I tried being smart about it but partially failed, but still an interesting find, so here it is:

import types
b = [i for i in dir(__builtins__) if isinstance(eval(i), types.BuiltinFunctionType)]

This returns a list of 42 items for me in python 3.5.3

Without using types, a nice seperator is to check if the items in __builtins__ start with a lowercase letter, that usually indicates a function, so

b = [i for i in dir(__builtins__) if i[0].islower()]

Returns 72 items for me, perhaps it's more complete than the documentation is? My guess would be yes. Check it out for yourself to test these ideas

Upvotes: 2

Related Questions