builtins 内建模块 / builtins Module


在Python的模块中,有一种特殊模块,无需导入便可以使用,其中包含了许多内建函数与类。

builtins 模块内容 / builtins Content


通过对 builtins 模块的导入(也可使用 __builtins__ 代替),可以利用 pdir 模块查看内部的函数与类及异常等。

pdir 模块是一个用于查看模块内部所有函数、类等信息的模块,安装方式为:

pip install pdir2

具体使用方式也十分简单,

 import builtins
import pdir
# Or print(pdir(__builtins__))
print(pdir(builtins))

最终输出如下,可以看到 builtins 模块中包含了所有的内置变量或函数等。

module attribute:
__loader__, __name__, __package__, __spec__
other:
Ellipsis, False, None, NotImplemented, True, __debug__, copyright, credits, exit, help, license, quit
special attribute:
__doc__
class:
BaseException: Common base class for all exceptions
GeneratorExit: Request that a generator exit.
KeyboardInterrupt: Program interrupted by user.
SystemExit: Request to exit from the interpreter.
bool: bool(x) -> bool
bytearray: bytearray(iterable_of_ints) -> bytearray
bytes: bytes(iterable_of_ints) -> bytes
classmethod: classmethod(function) -> method
complex: complex(real[, imag]) -> complex number
dict: dict() -> new empty dictionary
enumerate: enumerate(iterable[, start]) -> iterator for index, value of iterable
filter: filter(function or None, iterable) --> filter object
float: float(x) -> floating point number
frozenset: frozenset() -> empty frozenset object
int: int(x=0) -> integer
list: list() -> new empty list
map: map(func, *iterables) --> map object
memoryview: Create a new memoryview object which references the given object.
object: The most base type
property: property(fget=None, fset=None, fdel=None, doc=None) -> property attribute
range: range(stop) -> range object
reversed: reversed(sequence) -> reverse iterator over values of the sequence
set: set() -> new empty set object
slice: slice(stop)
staticmethod: staticmethod(function) -> method
str: str(object='') -> str
super: super() -> same as super(__class__, <first argument>)
tuple: tuple() -> empty tuple
type: type(object_or_name, bases, dict)
zip: zip(iter1 [,iter2 [...]]) --> zip object
exception:
ArithmeticError: Base class for arithmetic errors.
AssertionError: Assertion failed.
AttributeError: Attribute not found.
BlockingIOError: I/O operation would block.
BrokenPipeError: Broken pipe.
BufferError: Buffer error.
BytesWarning: Base class for warnings about bytes and buffer related problems, mostly
ChildProcessError: Child process error.
ConnectionAbortedError: Connection aborted.
ConnectionError: Connection error.
ConnectionRefusedError: Connection refused.
ConnectionResetError: Connection reset.
DeprecationWarning: Base class for warnings about deprecated features.
EOFError: Read beyond end of file.
EnvironmentError: Base class for I/O related errors.
Exception: Common base class for all non-exit exceptions.
FileExistsError: File already exists.
FileNotFoundError: File not found.
FloatingPointError: Floating point operation failed.
FutureWarning: Base class for warnings about constructs that will change semantically
IOError: Base class for I/O related errors.
ImportError: Import can't find module, or can't find name in module.
ImportWarning: Base class for warnings about probable mistakes in module imports
IndentationError: Improper indentation.
IndexError: Sequence index out of range.
InterruptedError: Interrupted by signal.
IsADirectoryError: Operation doesn't work on directories.
KeyError: Mapping key not found.
LookupError: Base class for lookup errors.
MemoryError: Out of memory.
NameError: Name not found globally.
NotADirectoryError: Operation only works on directories.
NotImplementedError: Method or function hasn't been implemented yet.
OSError: Base class for I/O related errors.
OverflowError: Result too large to be represented.
PendingDeprecationWarning: Base class for warnings about features which will be deprecated
PermissionError: Not enough permissions.
ProcessLookupError: Process not found.
RecursionError: Recursion limit exceeded.
ReferenceError: Weak ref proxy used after referent went away.
ResourceWarning: Base class for warnings about resource usage.
RuntimeError: Unspecified run-time error.
RuntimeWarning: Base class for warnings about dubious runtime behavior.
StopAsyncIteration: Signal the end from iterator.__anext__().
StopIteration: Signal the end from iterator.__next__().
SyntaxError: Invalid syntax.
SyntaxWarning: Base class for warnings about dubious syntax.
SystemError: Internal error in the Python interpreter.
TabError: Improper mixture of spaces and tabs.
TimeoutError: Timeout expired.
TypeError: Inappropriate argument type.
UnboundLocalError: Local name referenced but not bound to a value.
UnicodeDecodeError: Unicode decoding error.
UnicodeEncodeError: Unicode encoding error.
UnicodeError: Unicode related error.
UnicodeTranslateError: Unicode translation error.
UnicodeWarning: Base class for warnings about Unicode related problems, mostly
UserWarning: Base class for warnings generated by user code.
ValueError: Inappropriate argument value (of correct type).
Warning: Base class for warning categories.
WindowsError: Base class for I/O related errors.
ZeroDivisionError: Second argument to a division or modulo operation was zero.
function:
__build_class__: __build_class__(func, name, *bases, metaclass=None, **kwds) -> class
__import__: __import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
abs: Return the absolute value of the argument.
all: Return True if bool(x) is True for all values x in the iterable.
any: Return True if bool(x) is True for any x in the iterable.
ascii: Return an ASCII-only representation of an object.
bin: Return the binary representation of an integer.
callable: Return whether the object is callable (i.e., some kind of function).
chr: Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.
compile: Compile source into a code object that can be executed by exec() or eval().
delattr: Deletes the named attribute from the given object.
dir: dir([object]) -> list of strings
divmod: Return the tuple (x//y, x%y). Invariant: div*y + mod == x.
eval: Evaluate the given source in the context of globals and locals.
exec: Execute the given source in the context of globals and locals.
format: Return value.__format__(format_spec)
getattr: getattr(object, name[, default]) -> value
globals: Return the dictionary containing the current scope's global variables.
hasattr: Return whether the object has an attribute with the given name.
hash: Return the hash value for the given object.
hex: Return the hexadecimal representation of an integer.
id: Return the identity of an object.
input: Read a string from standard input. The trailing newline is stripped.
isinstance: Return whether an object is an instance of a class or of a subclass thereof.
issubclass: Return whether 'cls' is a derived from another class or is the same class.
iter: iter(iterable) -> iterator
len: Return the number of items in a container.
locals: Return a dictionary containing the current scope's local variables.
max: max(iterable, *[, default=obj, key=func]) -> value
min: min(iterable, *[, default=obj, key=func]) -> value
next: next(iterator[, default])
oct: Return the octal representation of an integer.
open: Open file and return a stream. Raise IOError upon failure.
ord: Return the Unicode code point for a one-character string.
pow: Equivalent to x**y (with two arguments) or x**y % z (with three arguments)
print: print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
repr: Return the canonical string representation of the object.
round: round(number[, ndigits]) -> number
setattr: Sets the named attribute on the given object to the specified value.
sorted: Return a new list containing all items from the iterable in ascending order.
sum: Return the sum of a 'start' value (default: 0) plus an iterable of numbers
vars: vars([object]) -> dictionary

builtins 的引用 / builtins Import


对于builtins模块一般使用 __builtins__ 进行引用,如果在 __main__ 模块内引用,则 __builtins__ 是对 builtins 模块的直接引用,而如果是在非 __main__ 模块中引用,则 __builtins__ 是对 builtins.__dict__ 的引用,而非本身,即返回的类型实质上是一个字典。

首先定义一个 Foo.py 文件,在文件中输入下面的代码

 print('__builtins__ called not in __main__, type is:', type(__builtins__))

然后在另一个文件中将 Foo 导入,并同样对 __builtins__ 的引用进行查看,

 import Foo
print('__builtins__ called in __main__, type is:', type(__builtins__))

最终的输出可以看到,在 Foo 中,__builtins__ 返回的是一个字典,而在当前模块中则返回的是 module,即 builtins 模块

__builtins__ called not in __main__, type is: <class 'dict'>
__builtins__ called in __main__, type is: <class 'module'>

Note: 这一特性在判断内置模块是否有某些函数的时候将会需要特别注意(常见于编写 Python2/3 都通用的代码时用于判断内置函数,如是否有 raw_input,从而对函数重新指向,使其通用于 Python2/3)。

参考链接


http://blog.sina.com.cn/s/blog_8a18c33d01019yek.html

Python的程序结构[5] -> 模块/Module[0] -> 内建模块 builtins的更多相关文章

  1. Python的程序结构[2] -> 类/Class[3] -> 内建类与内建函数

    内建类与内建函数的区分 / Distinction of Built-in Type and Function 对于 Python,有许多可以不需要定义或引用就可以使用的函数(类)(参考内建模块),诸 ...

  2. Python的程序结构[2] -> 类/Class[5] -> 内建类 bytes 和 bytearray

    内建类 bytes 和 bytearray / Built-in Type bytes and bytearray 关于内建类 Python的内建类 bytes 主要有以下几点: class byte ...

  3. Python的程序结构[2] -> 类/Class[6] -> 内建类 map

    内建类map / Built-in Type map 关于内建类 map 是一个内建的类,能够返回一个 map 的 obj.map 的第一个参数为一个可执行函数,后续参数均为可迭代对象,map 会分别 ...

  4. Python的程序结构[2] -> 类/Class[4] -> 内建类 super

    内建类 super / Built-in Type super 关于内建类 对于 super 可以从官方文档中看到基本介绍,super 接收一个类,以及类或类的实例,最终返回一个代理对象的实例.而 M ...

  5. Python的程序结构[3] -> 变量/Variable[0] -> 变量类型

    变量类型 / Variable Type 在 Python 中,变量主要有以下几种,即全局变量,局部变量和内建变量, 全局变量 / Global Variable 通常定义于模块内部,大写变量名形式存 ...

  6. Python的程序结构[1] -> 方法/Method[0] -> 类实例方法、私有方法和抽象方法

    类实例方法.私有方法和抽象方法 Python中最常用的就是类实例方法,类似于属性中的类实例属性,同时,也存在与私有属性类似方法,即私有方法,下面介绍这两种常见的方法,以及一种特殊意义的类实例方法 -- ...

  7. Python的程序结构[2] -> 类/Class[0] -> 类的特殊属性

    类的特殊属性 / Special Property of Class Python 中通过 class 进行类的定义,类可以实例化成实例并利用实例对方法进行调用. 类中还包含的一些共有的特殊属性. 特 ...

  8. Python的程序结构[4] -> 函数/Function[0] -> 函数与方法的区别

    函数与方法的区别 / Distinction of Function and Method 关于函数与方法的区别,可根据两者的定义看出, 函数function -- A series of state ...

  9. Python的程序结构[4] -> 函数/Function[1] -> 内建函数

    内建函数 / Built-in Function or Method Python中有许多的内建函数(查看内建模块部分),此处将对内建函数进行介绍 内建函数 ord / built-in functi ...

随机推荐

  1. python学习总结---面向对象2

    面向对象三大特点 - 封装:既是对数据结构的封装,有是处理数据的方法的封装. - 继承:强调的父子类的关系. - 多态:不同对象调用相同的方法,有不同的响应. 类的继承 - 相关概念 - 继承:父类的 ...

  2. Python全栈工程师(文件操作、编码)

    ParisGabriel                每天坚持手写  一天一篇  决定坚持几年 为了梦想为了信仰     Python人工智能从入门到精通 最近简直要死了 发烧感冒 喉咙痛..... ...

  3. Java对字符串进行加密

    package anli1; import java.util.Scanner; public class example { public static void main(String[]args ...

  4. SQL SERVER 2008 bug

    我把一个数据的数据导入的到另外一个数据库 作为 测试库使用. 发现里面设置为唯一标识ID  自动增长的表 全部默认是否. 最后只能手动一个个 表全部改过来. 弄了好久才发现这个问题.浪费了我几个小时的 ...

  5. CSS绘制三角形的原理剖析

    今天学习Bootstrap时候,看到按钮的向下三角形源码: .caret { display: inline-block; ; ; margin-left: 2px; vertical-align: ...

  6. Unity Shader-GodRay,体积光(BillBoard,Volume Shadow,Raidal Blur,Ray-Marching)

    好久没有更新博客了,经历了不少事情,好在最近回归了一点正轨,决定继续Unity Shader的学习之路.作为回归的第一篇,来玩一个比较酷炫的效果(当然废话也比较多),一般称之为GodRay(圣光),也 ...

  7. 自适应注意力机制在Image Caption中的应用

    在碎片化阅读充斥眼球的时代,越来越少的人会去关注每篇论文背后的探索和思考. 在这个栏目里,你会快速 get 每篇精选论文的亮点和痛点,时刻紧跟 AI 前沿成果. 点击本文底部的「阅读原文」即刻加入社区 ...

  8. [poj] 1389 Area of Simple Polygons

    原题 线段树+扫描线 对于这样一个不规则图形,我们要求他的面积有两种方法,割和补. 补显然不行,因为补完你需要求补上去的内部分不规则图形面积-- 那么怎么割呢? 像这样: 我们就转化成了无数个矩形的和 ...

  9. python request模板

    # -*- coding: utf-8 -*- import time import requests class Request: def __init__(self): self.s=reques ...

  10. clips 前端 js 单选按钮与输入框 的配合变化

    情形1: 一对单选按钮 一个输入框组 输入框组随单选按钮的改变而替换文字或执行其它 片段属于 介绍单选框的基本使用方式  : 1.单选框是有分类的,每个单选框有自己所属的组 从而一个页面可以拥有多组单 ...