2. Built-in Functions

Python 解释器内置了一些函数,它们总是可用的。这里将它们按字母表顺序列出。

Built-in Functions
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() __import__()
complex() hash() min() set() apply()
delattr() help() next() setattr() buffer()
dict() hex() object() slice() coerce()
dir() id() oct() sorted() intern()
abs(x)

返回一个数的绝对值。参数可以是普通的整数,长整数或者浮点数。如果参数是个复数,返回它的模。

all(iterable)

如果iterable的所有元素为真(或者iterable为空), 返回True等同于:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

出现于版本2.5。

any(iterable)

如果iterable的任一元素为真,返回True如果iterable为空,返回False等同于:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

出现于版本2.5。

basestring()

这个抽象类型是strunicode的超类。 它不能被调用或者实例化,但是可以用来测试一个对象是否是str或者unicode的实例。 isinstance(obj, basestring)等同于isinstance(obj, (str, unicode))

出现于版本2.3。

bin(x)

将一个整数转化成一个二进制字符串。结果是一个合法的Python表达式。如果x不是一个Python int对象,它必须定义一个返回整数的__index__()方法。

出现于版本2.6。

bool([x])

将一个值转化成布尔值,使用标准的真值测试例程。如果x为假或者没有参数,它返回False否则它返回Truebool也是一个类,它是int的子类。bool不能被继承。它唯一的实例就是FalseTrue

版本 2.2.1 新增。

改变于版本 2.3:如果没有参数,函数返回False

bytearray([source[, encoding[, errors]]])

返回一个新的字节数组。bytearray类型是一个可变的整数序列,整数范围为0 <= x < 256(即字节)。 它有可变序列的大多数方法,参见Mutable Sequence Types,同时它也有str类型的大多数方法,参见String Methods

source参数可以以不同的方式来初始化数组,它是可选的:

  • 如果是string,必须指明encoding(以及可选的errors)参数;bytearray()使用str.encode()将字符串转换为字节数组。
  • 如果是integer,生成相应大小的数组,元素初始化为空字节。
  • 如果是遵循buffer接口的对象,对象的只读buffer被用来初始化字节数组。
  • 如果是iterable,它的元素必须是整数,其取值范围为0 <= x < 256,用以初始化字节数组。

如果没有参数,它创建一个大小为0的数组。

出现于版本2.6。

callable(object)

如果object参数可调用,返回True;否则返回False如果返回真,对其调用仍有可能失败;但是如果返回假,对object的调用总是失败。注意类是可调用的(对类调用返回一个新实例);如果类实例有__call__()方法,则它们也是可调用的。

chr(i)

返回一个单字符字符串,字符的ASCII码为整数i例如,chr(97)返回字符串'a'它是ord()的逆运算。参数的取值范围为[0..255]的闭区间;如果i超出取值范围,抛出ValueError参见unichr()

classmethod(function)

function包装成类方法。

类方法接受类作为隐式的第一个参数,就像实例方法接受实例作为隐式的第一个参数一样。声明一个类方法,使用这样的惯例:

class C(object):
    @classmethod
    def f(cls, arg1, arg2, ...):
        ...

@classmethod是函数decorator(装饰器)参见Function definitions中的函数定义。

它即可以通过类来调用(如C.f()),也可以通过实例来调用(如C().f())。除了实例的类,实例本身被忽略。如果在子类上调用类方法,子类对象被传递为隐式的第一个参数。

类方法不同于C++或Java中的静态方法。如果你希望静态方法,参见这节的staticmethod()

需要类方法更多的信息,参见The standard type hierarchy中标准类型层次部分的文档。

版本 2.2 新增。

改变于版本2.4:添加了函数装饰器语法。

cmp(x, y)

比较两个对象xy,根据结果返回一个整数。如果x < y,返回负数;如果x == y,返回0;如果x > y,返回正数。

compile(source, filename, mode[, flags[, dont_inherit]])

Compile the source into a code or AST object. Code objects can be executed by an exec statement or evaluated by a call to eval(). source can either be a Unicode string, a Latin-1 encoded string or an AST object. Refer to the ast module documentation for information on how to work with AST objects.

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file ('<string>' is commonly used).

The mode argument specifies what kind of code must be compiled; 如果source包含一组语句,它是'exec';如果是单一的表达式,它是'eval';如果是单一的交互式语句,它是'single'。(对于最后一种情况,如果表达式语句的结果不是None,它的值会被打印)。

The optional arguments flags and dont_inherit control which future statements (see PEP 236) affect the compilation of source. If neither is present (or both are zero) the code is compiled with those future statements that are in effect in the code that is calling compile. If the flags argument is given and dont_inherit is not (or is zero) then the future statements specified by the flags argument are used in addition to those that would be used anyway. If dont_inherit is a non-zero integer then the flags argument is it – the future statements in effect around the call to compile are ignored.

Future statements are specified by bits which can be bitwise ORed together to specify multiple statements. The bitfield required to specify a given feature can be found as the compiler_flag attribute on the _Feature instance in the __future__ module.

This function raises SyntaxError if the compiled source is invalid, and TypeError if the source contains null bytes.

Note

When compiling a string with multi-line code in 'single' or 'eval' mode, input must be terminated by at least one newline character. This is to facilitate detection of incomplete and complete statements in the code module.

Changed in version 2.3: The flags and dont_inherit arguments were added.

Changed in version 2.6: Support for compiling AST objects.

Changed in version 2.7: Allowed use of Windows and Mac newlines. Also input in 'exec' mode does not have to end in a newline anymore.

complex([real[, imag]])

Create a complex number with the value real + imag*j or convert a string or number to a complex number. If the first parameter is a string, it will be interpreted as a complex number and the function must be called without a second parameter. The second parameter can never be a string. Each argument may be any numeric type (including complex). If imag is omitted, it defaults to zero and the function serves as a numeric conversion function like int(), long() and float(). If both arguments are omitted, returns 0j.

Note

When converting from a string, the string must not contain whitespace around the central + or - operator. For example, complex('1+2j') is fine, but complex('1 + 2j') raises ValueError.

The complex type is described in Numeric Types — int, float, long, complex.

delattr(object, name)

这个函数和setattr()有关。参数是一个对象和一个字符串。字符串必须是对象的某个属性的名字。只要对象允许,这个函数删除该名字对应的属性。例如,delattr(x, 'foobar')等同于del x.foobar

dict(**kwarg)
dict(mapping, **kwarg)
dict(iterable, **kwarg)

创建一个新字典。The dict object is the dictionary class. See dict and Mapping Types — dict for documentation about this class.

For other containers see the built-in list, set, and tuple classes, as well as the collections module.

dir([object])

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. 如果对象是自定义的话,返回列表有可能不完整或不准确__getattr__()

The default dir() mechanism behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:

  • If the object is a module object, the list contains the names of the module’s attributes.
  • If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
  • Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

The resulting list is sorted alphabetically. For example:

>>> import struct
>>> dir()   # show the names in the module namespace
['__builtins__', '__doc__', '__name__', 'struct']
>>> dir(struct)   # show the names in the struct module
['Struct', '__builtins__', '__doc__', '__file__', '__name__',
 '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into',
 'unpack', 'unpack_from']
>>> class Shape(object):
        def __dir__(self):
            return ['area', 'perimeter', 'location']
>>> s = Shape()
>>> dir(s)
['area', 'perimeter', 'location']

Note

Because dir() is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.

divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using long division. With mixed operand types, the rules for binary arithmetic operators apply. 对于普通整数或者长整数,结果等同于(a // b, a % b)For floating point numbers the result is (q, a % b), where q is usually math.floor(a / b) but may be 1 less than that. In any case q * b + a % b is very close to a, if a % b is non-zero it has the same sign as b, and 0 <= abs(a % b) < abs(b).

Changed in version 2.3: Using divmod() with complex numbers is deprecated.

enumerate(sequence, start=0)

Return an enumerate object. sequence必须是序列或迭代器iterator,或者支持迭代的对象。The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

Equivalent to:

def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

版本 2.3 新增。

Changed in version 2.6: 添加了 start 参数。

eval(expression[, globals[, locals]])

The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

Changed in version 2.4: formerly locals was required to be a dictionary.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard __builtin__ module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:

>>> x = 1
>>> print eval('x+1')
2

This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be None.

Hints: dynamic execution of statements is supported by the exec statement. Execution of statements from a file is supported by the execfile() function. The globals() and locals() functions returns the current global and local dictionary, respectively, which may be useful to pass around for use by eval() or execfile().

See ast.literal_eval() for a function that can safely evaluate strings with expressions containing only literals.

execfile(filename[, globals[, locals]])

This function is similar to the exec statement, but parses a file instead of a string. It is different from the import statement in that it does not use the module administration — it reads the file unconditionally and does not create a new module. [1]

The arguments are a file name and two optional dictionaries. The file is parsed and evaluated as a sequence of Python statements (similarly to a module) using the globals and locals dictionaries as global and local namespace. If provided, locals can be any mapping object. Remember that at module level, globals and locals are the same dictionary. If two separate objects are passed as globals and locals, the code will be executed as if it were embedded in a class definition.

Changed in version 2.4: formerly locals was required to be a dictionary.

If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where execfile() is called. The return value is None.

Note

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function execfile() returns. execfile() cannot be used reliably to modify a function’s locals.

file(name[, mode[, buffering]])

Constructor function for the file type, described further in section File Objects. The constructor’s arguments are the same as those of the open() built-in function described below.

When opening a file, it’s preferable to use open() instead of invoking this constructor directly. file is more suited to type testing (for example, writing isinstance(f, file)).

版本 2.2 新增。

filter(function, iterable)

Construct a list from those elements of iterable for which function returns true. iterable可以是个序列,支持迭代的容器,或者一个迭代器。如果iterable是个字符串或者元组,则结果也是字符串或者元组;否则结果总是列表。如果functionNone,使用特性函数,即为假的iterable被移除。

注意,在function不为None的情况下,filter(function, iterable)等同于[item for item in iterable if function(item)];否则等同于[item for item in iterable if item](function为None)。

参见itertools.ifilter()itertools.ifilterfalse(),以得到该函数的迭代器版本,以及该函数的变体(过滤function返回假的元素)。

float([x])

将字符串或者数字转化成浮点数。如果参数是字符串,它必须包含小数或者浮点数(可以有符号),周围可以有空白。参数也可以是[+|-]nan或者[+|-]inf。其它情况下,参数可以是原始/长整数或者浮点数,(以Python的浮点数精度)返回具有相同值的浮点数。如果没有参数,返回0.0

注意

当传递字符串时,依赖于底层的C库,可以返回NaN(Not a Number,不是一个数字)和Infinity(无穷大)这样的值。该函数接受字符串nan(NaN),inf(正无穷大)和-inf(负无穷大)。对于NaN,不区分大小写和+/-号。总是用nan,inf或者-inf来表示NaN和Infinity。

float类型描述于Numeric Types — int, float, long, complex

format(value[, format_spec])

value转化成“格式化”的表现形式,格式由format_spec控制。format_spec的解释依赖于value参数的类型,大多数内置类型有标准的格式化语法:Format Specification Mini-Language

注意

format(value, format_spec)仅仅呼叫value.__format__(format_spec)

版本 2.6 新增。

frozenset([iterable])

返回一个新的frozenset对象,如果可选参数iterable存在,frozenset的元素来自于iterable。frozenset是个内置类。参见frozensetSet Types — set, frozenset

关于其它容器,参见setlisttuple,和dict类,以及collections模块。

版本 2.4 新增。

getattr(object, name[, default])

返回object的属性值。name必须是个字符串。如果字符串是对象某个属性的名字,则返回该属性的值。例如,getattr(x, 'foobar')等同于x.foobar如果名字指明的属性不存在,且有default参数,default被返回;否则抛出AttributeError

globals()

返回表示当前全局符号表的字典。它总是当前模块的字典(在函数或者方法中,它指定义的模块而不是调用的模块)。

hasattr(object, name)

参数时一个对象和一个字符串。如果字符串时对象某个属性的名字,返回True;否则返回False(实现方式为调用getattr(object, name),看它是否抛出异常)。

hash(object)

返回对象的hash(哈希/散列)值(如果有的话)。hash值是整数。它被用于在字典查找时快速比较字典的键。相同的数值有相同的hash(尽管它们有不同的类型,比如1和1.0)。

help([object])

调用内置的帮助系统。(这个函数主要用于交互式使用。)如果没有参数,在解释器的控制台启动交互式帮助系统。如果参数是个字符串,该字符串被当作模块名,函数名,类名,方法名,关键字或者文档主题而被查询,在控制台上打印帮助页面。如果参数是其它某种对象,生成关于对象的帮助页面。

这个函数经由site模块加入内置的命名空间。

版本 2.2 新增。

hex(x)

将任意大小的整数转化成以“0x”打头的小写的十六进制字符串,例如:

>>> hex(255)
'0xff'
>>> hex(-42)
'-0x2a'
>>> hex(1L)
'0x1L'

如果x不是Python的int或者long对象,它必须定义__index__()方法以返回一个整数。

参见int(),它将十六进制字符串转化成一个整数。

注意

使用float.hex()方法得到浮点数的十六进制字符串表示。

改变于版本2.4:在此之前只返回无符号数。

id(object)

Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

input([prompt])

Equivalent to eval(raw_input(prompt)).

This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. 如果执行中有错误,将抛出其它异常。

If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.

建议使用raw_input()函数来得到用户的一般输入。

int(x=0)
int(x, base=10)

将数字或字符串x转化成一个整数,如果没有参数则返回0如果x是个数字,它可以是普通整数/长整数,或者浮点数。If x is floating point, the conversion truncates towards zero. If the argument is outside the integer range, the function returns a long object instead.

If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35. The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O/0, or 0x/0X, as with integer literals in code. Base 0 means to interpret the string exactly as an integer literal, so that the actual base is 2, 8, 10, or 16.

The integer type is described in Numeric Types — int, float, long, complex.

isinstance(object, classinfo)

如果参数object 是参数classinfo 的一个实例;或者是其一个(直接的、间接的或者virtual)子类的实例,返回真。Also return true if classinfo is a type object (new-style class) and object is an object of that type or of a (direct, indirect or virtual) subclass thereof. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised.

Changed in version 2.2: Support for a tuple of type information was added.

issubclass(class, classinfo)

Return true if class is a subclass (direct, indirect or virtual) of classinfo. A class is considered a subclass of itself. classinfo may be a tuple of class objects, in which case every entry in classinfo will be checked. In any other case, a TypeError exception is raised.

Changed in version 2.3: Support for a tuple of type information was added.

iter(o[, sentinel])

Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. 如果没有第二个参数,o必须是一个支持迭代协议(即 __iter__()方法)或序列协议(即__getitem__()方法,整数参数从0开始)的对象。If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

One useful application of the second form of iter() is to read lines of a file until a certain line is reached. The following example reads a file until the readline() method returns an empty string:

with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

New in version 2.2.

len(s)

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

list([iterable])

Return a list whose items are the same and in the same order as iterable‘s items. iterable may be either a sequence, a container that supports iteration, or an iterator object. If iterable is already a list, a copy is made and returned, similar to iterable[:]. For instance, list('abc') returns ['a', 'b', 'c'] and list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, returns a new empty list, [].

list is a mutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built in dict, set, and tuple classes, and the collections module.

locals()

Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.

Note

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

long(x=0)
long(x, base=10)

Convert a string or number to a long integer. 如果参数是个字符串,它必须包含一个数字,任意大小,可以有符号,周围可以有空白。The base argument is interpreted in the same way as for int(), and may only be given when x is a string. Otherwise, the argument may be a plain or long integer or a floating point number, and a long integer with the same value is returned. Conversion of floating point numbers to integers truncates (towards zero). If no arguments are given, returns 0L.

The long type is described in Numeric Types — int, float, long, complex.

map(function, iterable, ...)

function应用于iterable的每一个元素,返回结果的列表。如果有额外的iterable参数,并行的从这些参数中取元素,并调用function如果一个参数比另外的要短,将以None扩展该参数元素。如果functionNone使用特性函数;如果有多个参数,map()返回一元组列表,元组包含从各个参数中取得的对应的元素(某种变换操作)。iterable参数可以是序列或者任意可迭代对象;结果总是列表。

max(iterable[, key])
max(arg1, arg2, *args[, key])

返回可迭代的对象中的最大的元素,或者返回2个或多个参数中的最大的参数。

如果有一个位置参数,iterable必须是个非空的可迭代对象(如非空字符串,元组或者列表)。返回可迭代对象中最大的元素。如果有2个或更多的位置参数,返回最大位置参数。

可选的key参数指明了有一个参数的排序函数,如list.sort()中使用的排序函数。如果有key参数,它必须是关键字参数(例如,max(a,b,c,key=func))。

改变于版本2.5:添加了对可选参数key的支持。

memoryview(obj)

返回给定参数的“memory view”对象。参见memoryview type

min(iterable[, key])
min(arg1, arg2, *args[, key])

返回可迭代的对象中的最小的元素,或者返回2个或多个参数中的最小的参数。

如果有一个位置参数,iterable必须是个非空的可迭代对象(如非空字符串,元组或者列表)。返回可迭代对象中最小的元素。如果有2个或更多的位置参数,返回最小的位置参数。

可选的key参数指明了有一个参数的排序函数,如list.sort()中使用的排序函数。如果有key参数,它必须是关键字参数(例如,min(a,b,c,key=func))。

改变于版本2.5:添加了对可选参数key的支持。

next(iterator[, default])

通过调用iteratornext()方法,得到它的下一个元素。If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.

New in version 2.6.

object()

Return a new featureless object. object is a base for all new style classes. It has the methods that are common to all instances of new style classes.

New in version 2.2.

Changed in version 2.3: 该函数不接受任何的参数。Formerly, it accepted arguments but ignored them.

oct(x)

Convert an integer number (of any size) to an octal string. The result is a valid Python expression.

Changed in version 2.4: Formerly only returned an unsigned literal.

open(name[, mode[, buffering]])

打开一个文件,返回一个file类型的对象,file类型描述于File Objects章节。If the file cannot be opened, IOError is raised. When opening a file, it’s preferable to use open() instead of invoking the file constructor directly.

The first two arguments are the same as for stdio‘s fopen(): name is the file name to be opened, and mode is a string indicating how the file is to be opened.

The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to 'r'. The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode

The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes). A negative buffering means to use the system default, which is usually line buffered for tty devices and fully buffered for other files. If omitted, the system default is used. [2]

Modes 'r+', 'w+' and 'a+' open the file for updating (reading and writing); note that 'w+' truncates the file. Append 'b' to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the 'b' has no effect.

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newlines support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'.All of these external representations are seen as '\n' by the Python program. If Python is built without universal newlines support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

Python enforces that the mode, after stripping 'U', begins with 'r', 'w' or 'a'.

Python provides many file handling modules including fileinput, os, os.path, tempfile, and shutil.

Changed in version 2.5: Restriction on first letter of mode string introduced.

ord(c)

Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be ra

pow(x, y[, z])

Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z). The two-argument form pow(x, y) is equivalent to using the power operator: x**y.

The arguments must have numeric types. With mixed operand types, the coercion rules for binary arithmetic operators apply. For int and long int operands, the result has the same type as the operands (after coercion) unless the second argument is negative; in that case, all arguments are converted to float and a float result is delivered. For example, 10**2 returns 100, but 10**-2 returns 0.01. (This last feature was added in Python 2.2. In Python 2.1 and before, if both arguments were of integer types and the second argument was negative, an exception was raised.) If the second argument is negative, the third argument must be omitted. If z is present, x and y must be of integer types, and y must be non-negative. (This restriction was added in Python 2.2. In Python 2.1 and before, floating 3-argument pow() returned platform-dependent results depending on floating-point rounding accidents.)

print(*objects, sep=' ', end='\n', file=sys.stdout)

sep分割,end的值结尾,将对象打印到文件流中。sep, end and file, if present, must be given as keyword arguments.

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Output buffering is determined by file. Use file.flush() to ensure, for instance, immediate appearance on a screen.

注意

这个函数一般不会被作为内置函数可用,因为print被识别为print语句。为了使得print语句失效,而使用 print() 函数, 可以在你的模块上面使用future 语句:

from __future__ import print_function

版本 2.6 新增。

property([fget[, fset[, fdel[, doc]]]])

返回新式类(继承自object的类)的一个Property 性质的属性。

fget是用于获取属性值的函数,类似地fset用于设置属性,fdel用于删除属性。典型的用法是定义一个托管的属性x

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

假设cC的一个实例,c.x将调用获取函数,c.x = value调用设置函数,del c.x调用删除函数。

如果给出doc,它将是该属性的文档字符串。否则,该属性将拷贝fget的文档字符串(如果存在)。这使得用property()作为装饰器创建一个只读属性非常容易:

class Parrot(object):
    def __init__(self):
        self._voltage = 100000

    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

上面的例子将voltage() 方法转换为一个名称相同的只读属性。

Property 性质的属性具有gettersetterdeleter 方法,它们可以用做装饰器来创建该属性的拷贝,使得被修饰的函数为访问函数。This is best explained with an example:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

This code is exactly equivalent to the first example. Be sure to give the additional functions the same name as the original property (x in this case.)

返回的属性同样有构造函数参数中的fgetfsetfdel

New in version 2.2.

Changed in version 2.5: Use fget‘s docstring if no doc given.

Changed in version 2.6: The getter, setter, and deleter attributes were added.

range(stop)
range(start, stop[, step])

这是一个创建包含数列的列表的通用函数。It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised). Example:

>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
raw_input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. 示例:

>>> s = raw_input('--> ')
--> Monty Python's Flying Circus
>>> s
"Monty Python's Flying Circus"

如果已经加载readline模块,那么raw_input()将用它来提供优雅的行编辑和历史功能。

reduce(function, iterable[, initializer])

将带有两个参数的function累计地应用到iterable的元素上,从左向右,以致将可迭代序列归纳为一个单一的值。For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        try:
            initializer = next(it)
        except StopIteration:
            raise TypeError('reduce() of empty sequence with no initial value')
    accum_value = initializer
    for x in it:
        accum_value = function(accum_value, x)
    return accum_value
reload(module)

重新加载之前已经引入过的模块参数必须是一个模块对象,所以之前它必须成功导入过。如果你用外部编辑器编辑了模块的源文件并且打算在不离开python解释器的情况下使用该模块的新版本,reload将非常有用。返回值是该模块对象(与module参数相同)。

When reload(module) is executed:

  • Python模块的代码将重新编译并且模块级的代码会重新执行,定义一系列对象,这些对象被绑定到模块字典中对应的名字。改进后的模块的 init 函数不会第二次加载。
  • 跟Python其他对象一样,旧的对象只有在他们的引用计数降为0的时候被系统收回。
  • 模块命名空间中的名字自动升级指向新的或者修改后的对象。
  • 对旧对象的其他引用(比如模块外部的名字)不会连接到新的对象。每一个命名空间在被请求的时候,都必须更新。

这里有一些其他警告:

如果模组语法正确但是初始化失败,则第一次的import 声明不会在局部屏蔽它的名字,但会在 sys.modules中储存一个局部初始化的模组对象。如果需要重新加载模块 reload() 则需要import 一次。(this will bind the name to the partially initialized module object)

一个模组被重新加载以后,它的字典(包涵模组的全局变量)仍然被保留。重定义的名称将覆盖旧的定义,因此,这基本上不是个问题.如果一个模块的新版本没有定义由旧版本定义的名称,仍然用旧定义。此功能可用于模块的优势,如果它维护一个全局表或对象的缓存 — — try 语句可以测试,如果需要则跳过它的初始化︰

try:
    cache
except NameError:
    cache = {}

除了 sys__main____builtin__以外,一般情况下重新加载内建或者动态加载模组不是特别有用,但却是合法的。然而,很多情况下,扩展的模组并不支持再次初始化,并可能在重新加载的时候陷入任意路径。

如果一个模组用 from ... 从其他模组引入对象,import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

repr(object)

Return a string containing a printable representation of an object. 它与字符串转换式(反引号)产生的值相同。有时候能够把这个操作作为一个普通的函数访问非常有用。For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. 类可以通过定义__repr__()方法控制该函数对其实例的返回。

reversed(seq)

返回一个反向迭代器seq must be an object which has a __reversed__() method or supports the sequence protocol (the __len__() method and the __getitem__() method with integer arguments starting at 0).

New in version 2.4.

Changed in version 2.6: Added the possibility to write a custom __reversed__() method.

round(number[, ndigits])

返回一个浮点型 近似值,保留小数点后 ndigits 位。If ndigits is omitted, it defaults to zero. The result is a floating point number. 数值被四舍五入为功率减去ndigits的最接近的倍数10。如果有两个倍数离的一样近,结果取离0较远的(所以,例如,round(0.5)1.0round(-0.5)-1.0)。

Note

The behavior of round() for floats can be surprising: for example, round(2.675, 2) gives 2.67 instead of the expected 2.68. 这不是一个错误:这是由于大部分十进制小数不能用浮点数精确表示所造成的结果。See Floating Point Arithmetic: Issues and Limitations for more information.

set([iterable])

Return a new set object, optionally with elements taken from iterable. set is a built-in class. See set and Set Types — set, frozenset for documentation about this class.

For other containers see the built-in frozenset, list, tuple, and dict classes, as well as the collections module.

版本 2.4 新增。

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

slice(stop)
slice(start, stop[, step])

Return a slice object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example: a[start:stop:step] or a[start:stop, i]. See itertools.islice() for an alternate version that returns an iterator.

sorted(iterable[, cmp[, key[, reverse]]])

Return a new sorted list from the items in iterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method (described in section Mutable Sequence Types).

cmp指定一个自定义的带有两个参数的比较函数(可迭代的元素),它应该根据第一个参数是小于、等于还是大于第二个参数返回负数、零或者正数:cmp=lambda x,y: cmp(x.lower(), y.lower())The default value is None.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much faster than specifying an equivalent cmp function. This is because cmp is called multiple times for each list element while key and reverse touch each element only once. Use functools.cmp_to_key() to convert an old-style cmp function to a key function.

For sorting examples and a brief sorting tutorial, see Sorting HowTo.

版本 2.4 新增。

staticmethod(function)

Return a static method for function.

静态方法不接受隐式的第一个参数(也就是实例名称self)。To declare a static method, use this idiom:

class C(object):
    @staticmethod
    def f(arg1, arg2, ...):
        ...

The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details.

It can be called either on the class (such as C.f()) or on an instance (such as C().f()). 除了它的类型,实例其他的内容都被忽略。

Static methods in Python are similar to those found in Java or C++. Also see classmethod() for a variant that is useful for creating alternate class constructors.

For more information on static methods, consult the documentation on the standard type hierarchy in The standard type hierarchy.

New in version 2.2.

Changed in version 2.4: Function decorator syntax added.

str(object='')

返回一个字符串,包含对象的友好的可打印表示形式。对于字符串,它返回字符串本身。repr(object)的区别是str(object)不会永远试图返回一个eval()可接受的字符串;它的目标是返回一个可打印的字符串。如果没有给出参数,则返回空字符串''

关于字符串更多的信息请参阅序列类型 — str, unicode, list, tuple, bytearray, buffer, xrange,它了描述“序列”功能(字符串是序列的一种),以及在String Methods 一节中描述的字符串自己的方法。To output formatted strings use template strings or the % operator described in the String Formatting Operations section. In addition see the String Services section. 另请参阅unicode()

sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string.

For some use cases, there are good alternatives to sum(). The preferred, fast way to concatenate a sequence of strings is by calling '.join(sequence). To add floating point values with extended precision, see math.fsum(). To concatenate a series of iterables, consider using itertools.chain().

New in version 2.3.

super(type[, object-or-type])

返回一个代理对象,这个对象指派方法给一个父类或者同. 这对进入类中被覆盖的继承方法非常有用。搜索顺序和 getattr() 一样。而它自己的 类型 则被忽略。

type__mro__属性罗列了用getattr()super()来搜索排序的解决方法。它可以随着继承关系的变化,动态的更新。

如果没有第二个参数,则返回未绑定的super对象 如果第二个参数是object,则isinstance(obj, type)必须为true。如果第二个参数是type,issubclass(type2, type)必须为true(这对类方法很有用)。

注意

super() 仅适用于 新式类

super 函数有两种典型用例。在具有单继承的类层次结构中,可以使用super来引用父类,而不必明确命名它们,从而使代码更易于维护。这种使用方法非常类似于在其他编程语言中使用super

第二种用例是在动态执行环境中支持多继承。此用例是Python独有的,在静态编译语言或仅支持单继承的语言中找不到。这使得可以实现“diamond diagrams”,其中多个基类实现相同的方法。良好的设计表明此方法在每种情况下具有相同的调用签名(因为调用的顺序是在运行时确定的,因为该顺序适应类层次结构中的更改,并且因为该顺序可以包含在运行时之前未知的同胞类)。

对于这两种用例,典型的超类调用看起来像这样:

class C(B):
    def method(self, arg):
        super(C, self).method(arg)

注意,super()是作为使用显式的点属性查找(例如super().__ getitem __(name)的绑定过程的一部分)。它通过实现自己的__ getattribute __()方法来实现这一点,以便以支持协作多继承的可预测顺序来搜索类。因此,使用诸如super()[name]之类的语句或操作符时,super()是未定义的。

还要注意,super()不限于在方法内部使用。两个参数形式准确的指定参数,并进行适当的引用。

有关如何使用super()设计协同类的实用建议,请参阅使用super()的指南。

版本 2.2 新增。

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items. iterable may be a sequence, a container that supports iteration, or an iterator object. If iterable is already a tuple, it is returned unchanged. For instance, tuple('abc') returns ('a', 'b', 'c') and tuple([1, 2, 3]) returns (1, 2, 3). If no argument is given, returns a new empty tuple, ().

tuple is an immutable sequence type, as documented in Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange. For other containers see the built in dict, list, and set classes, and the collections module.

type(object)
type(name, bases, dict)

With one argument, return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the __name__ attribute; the bases tuple itemizes the base classes and becomes the __bases__ attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the __dict__ attribute. For example, the following two statements create identical type objects:

>>> class X(object):
...     a = 1
...
>>> X = type('X', (object,), dict(a=1))

版本 2.2 新增。

unichr(i)

Return the Unicode string of one character whose Unicode code is the integer i. For example, unichr(97) returns the string u'a'. This is the inverse of ord() for Unicode strings. The valid range for the argument depends how Python was configured – it may be either UCS2 [0..0xFFFF] or UCS4 [0..0x10FFFF]. ValueError is raised otherwise. For ASCII and 8-bit strings see chr().

版本 2.0 新增。

unicode(object='')
unicode(object[, encoding[, errors]])

Return the Unicode string version of object using one of the following modes:

如果给出encoding和/或errors参数,unicode()方法将解码对象,这个对象可以是8位字符串或使用encoding编解码器的字符缓冲区。encoding参数是一个表示编码名称的字符串;如果编码未知,则会引发LookupError错误。根据errors完成错误处理;这指定了在输入编码中无效字符串的处理方式。如果errors参数是'strict'(默认值),则会引发ValueError错误,如果是'ignoret'则导致错误被安静地忽略,如果是'replace'会导致使用官方的Unicode替代字符U+FFFD来替换不能被解码的输入字符串。另请参阅codecs模块。

如果没有给出可选的参数,则unicode()将模仿str()的行为,但是它返回Unicode字符串而不是8位字符串。更确切地说,如果object是一个Unicode字符串或其子类,它将返回该Unicode字符串,而不应用任何其他解码。

对于提供__ unicode __()方法的对象,将不带参数调用此方法来创建一个Unicode字符串。对于所有其他对象,要求提供8位字符串版本或表示,然后在'strict'模式下使用默认编码的编解码器将其转换为Unicode字符串。

有关Unicode字符串的详细信息,请参阅Sequenct Types - str,unicode,list,tuple,bytearray,buffer,xrange,其中描述了“序列”功能(Unicode字符串是序列),在 String Methods部分描述了字符串本身有关的方法。要输出格式化的字符串,请使用模板字符串或运算符,这部分内容在String Formatting Operations有描述。此外,请参阅String Services部分。另请参阅 str()

版本 2.0 新增。

版本 2.2 变更:添加了对 __unicode__() 的支持。

vars([object])

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

xrange(stop)
xrange(start, stop[, step])

This function is very similar to range(), but returns an xrange object instead of a list. This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously. The advantage of xrange() over range() is minimal (since xrange() still has to create the values when asked for them) except when a very large range is used on a memory-starved machine or when all of the range’s elements are never used (such as when the loop is usually terminated with break). For more information on xrange objects, see XRange Type and Sequence Types — str, unicode, list, tuple, bytearray, buffer, xrange.

CPython implementation detail: xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (“short” Python integers), and also requires that the number of elements fit in a native C long. If a larger range is needed, an alternate version can be crafted using the itertools module: islice(count(start, step), (stop-start+step-1+2*(step<0))//step).

zip([iterable, ...])

该函数返回一个以元组为元素的列表,其中第 i 个元组包含每个参数序列的第 i 个元素。返回的列表长度被截断为最短的参数序列的长度。当多个参数都具有相同的长度时,zip()类似于带有一个初始参数为Nonemap()只有一个序列参数时,它返回一个1元组的列表。没有参数时,它返回一个空的列表。

可以保证迭代按从左向右的计算顺序。This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n).

zip()* 操作符一起可以用来 unzip 一个列表:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

版本 2.0 新增。

版本 2.4 变更:以前,zip() 要求至少一个参数,且 zip() 抛出一个 TypeError 异常,而不是一个空的列表。

__import__(name[, globals[, locals[, fromlist[, level]]]])

Note

importlib.import_module() 不同,这是一个高级的函数,不会在日常的 Python 编程中用到。

它是通过 import 语句调用的.It can be replaced (by importing the __builtin__ module and assigning to __builtin__.__import__) in order to change semantics of the import statement, but nowadays it is usually simpler to use import hooks (see PEP 302). Direct use of __import__() is rare, except in cases where you want to import a module whose name is only known at runtime.

The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.

level specifies whether to use absolute or relative imports. The default is -1 which indicates both absolute and relative imports will be attempted. 0 means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__().

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.

For example, the statement import spam results in bytecode resembling the following code:

spam = __import__('spam', globals(), locals(), [], -1)

The statement import spam.ham results in this call:

spam = __import__('spam.ham', globals(), locals(), [], -1)

Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.

On the other hand, the statement from spam.ham import eggs, sausage as saus results in

_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage

Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.

If you simply want to import a module (potentially within a package) by name, use importlib.import_module().

版本 2.5 变更:添加了 level 参数。

版本 2.5 变更:添加了对关键字参数的支持。

3. Non-essential Built-in Functions

有几个内建的函数在现代Python编程中已经没有必要再学习、知道和使用了。这里保留它们是为了保持为老版本Python编写的程序的向后兼容。

Python程序员、培训人员、学生以及书籍编写人员应该自由跳过这些函数而不用担心遗漏重要的内容。

apply(function, args[, keywords])

The function argument must be a callable object (a user-defined or built-in function or method, or a class object) and the args argument must be a sequence. The function is called with args as the argument list; the number of arguments is the length of the tuple. If the optional keywords argument is present, it must be a dictionary whose keys are strings. It specifies keyword arguments to be added to the end of the argument list. Calling apply() is different from just calling function(args), since in that case there is always exactly one argument. The use of apply() is equivalent to function(*args, **keywords).

自2.3版后废弃: 使用function(*args, **keywords)来代替apply(function, args, keywords)(参见Unpacking Argument Lists)。

buffer(object[, offset[, size]])

object 参数必须是一个支持缓冲区调用接口的对象(例如字符串、数组和缓冲区)。A new buffer object will be created which references the object argument. The buffer object will be a slice from the beginning of object (or from the specified offset). The slice will extend to the end of object (or will have a length given by the size argument).

coerce(x, y)

Return a tuple consisting of the two numeric arguments converted to a common type, using the same rules as used by arithmetic operations. If coercion is not possible, raise TypeError.

intern(string)

Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy.Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys.

Changed in version 2.3: Interned strings are not immortal (like they used to be in Python 2.2 and before); you must keep a reference to the return value of intern() around to benefit from it.

Footnotes

[1]It is used relatively rarely so does not warrant being made into a statement.
[2]Specifying a buffer size currently has no effect on systems that don’t have setvbuf(). The interface to specify the buffer size is not done using a method that calls setvbuf(), because that may dump core when called after any I/O has been performed, and there’s no reliable way to determine whether this is the case.
[3]In the current implementation, local variable bindings cannot normally be affected this way, but variables retrieved from other scopes (such as modules) can be. This may change.