8.1. Built-in Types
This section documents Python's core built-in
types, such as int, float, dict, and many others. More details about many of these types, and about operations on their instances, are found throughout Chapter 4. In the rest of this section, by "number" I mean, specifically, "noncomplex number."
basestring | basestring
Noninstantiable (abstract) common basetype of types str and unicode. Used mostly to ascertain whether some object x is a string (either plain or Unicode) by testing isinstance(x, basestring).
| bool | bool(x)
Returns False if argument x evaluates as false; returns TRue if argument x evaluates as true. (See also "Boolean Values" on page 45.) bool is a subclass of int, and built-in names False and TRue refer to the only two instances of type bool. These instances are also integer numbers, equal to 0 and 1, respectively, but str(True) is 'TRue', and str(False) is 'False'.
| buffer | buffer(obj,offset=0,size=-1)
Returns a read-only buffer object that refers to a compact slice of obj's data, starting at the given offset and with the given size (all the way to the end of obj's data, if size<0, or if obj's data is too short to provide size bytes after the offset). obj must be of a type that supports the buffer call interface, such as a string or array.
| classmethod | classmethod(function)
Returns a class method object. In practice, you call this built-in type only within a class body, and, most often, in Python 2.4, you use it as a decorator. See "Class methods" on page 99.
| complex | complex(real,imag=0)
Converts any number, or a suitable string, to a complex number. imag may be present only when real is a number and is the imaginary part of the resulting complex number. See also "Complex numbers" on page 40.
| dict | dict(x={ })
Returns a new dictionary object with the same items as argument x. (Dictionaries are covered in "Dictionaries" on page 44.) When x is a dictionary, dict(x) returns a copy of x, like x.copy( ) does. Alternatively, x can be an iterable whose items are pairs (iterables with two items each). In this case, dict(x) returns a dictionary whose keys are the first items of each pair in x, while the values are the corresponding second items. In other words, when x is a sequence, c=dict(x) has the same effect as the following:
c = {}
for key, value in x: c[key] = value
You can also call dict with named arguments in addition to, or instead of, positional argument x. Each named argument becomes an additional item in the resulting dictionary, with the name as the key, possibly overwriting an item coming from x.
| enumerate | enumerate(iterable)
Returns a new iterator object whose items are pairs. For each such pair, the second item is the corresponding item in iterable, while the first item is an integer: 0, 1, 2.... For example, the following snippet loops on a list L of integers, halving each even value:
for i,num in enumerate(L):
if num % 2 == 0:
L[i] = num // 2
| file, open | file(path,mode='r',bufsize=-1)
open(filename,mode='r',bufsize=-1)
Opens or creates a file and returns a new file object. See "File Objects" on page 216.
| float | float(x)
Converts any number, or a suitable string, to a floating-point number. See "Floating-point numbers"
on page 39.
| frozenset | frozenset(seq=[ ])
Returns a new frozen (immutable) set object with the same items as the iterable object seq. When seq is a frozen set, frozenset(seq) returns seq itself, like seq.copy( ) does. See "Set Operations" on page 58.
| int | int(x[,radix])
Converts any number, or a suitable string, to an int. When x is a number, int truncates toward 0, dropping any fractional part. radix may be present only when x is a string. radix is the conversion base, between 2 and 36, with 10 as the default. radix can be explicitly passed as 0: the base is then 8, 10, or 16, depending on the form of string x, just like for integer literals, as covered in "Integer numbers" on page 39.
| list | list(seq=[ ])
Returns a new list object with the same items as the iterable object seq, in the same order. When seq is a list, list(seq) returns a copy of seq, like seq[:] does. See "Lists" on page 43.
| long | long(x[,radix])
Converts any number, or a suitable string, to a long. The rules regarding the radix argument are exactly the same as for int. See "Integer numbers" on page 39.
| object | object( )
Returns a new instance of the most fundamental type. Such direct instances of type object have no functionality, so the only practical reason to create one is to obtain a "sentinel" object, i.e., one guaranteed to compare unequal to any distinct object.
| property | property(fget=None,fset=None,fdel=None,doc=None)
Returns a property descriptor. In practice, you call this built-in type only within a class body. See "Properties" on page 100.
| reversed | reversed(seq)
Returns a new iterator object whose items are the items of sequence seq (which must be a proper sequence, not just any iterable) in reverse order.
| set | set(seq=[ ])
Returns a new mutable set object with the same items as the iterable object seq. When seq is a set, set(seq) returns a copy of seq, like seq.copy( ) does. See "Sets" on page 43.
| slice | slice([start,]stop[,step])
Returns a slice object
with read-only attributes start, stop, and step bound to the respective argument values, each defaulting to None when missing. Such a slice is essentially meant to signify the same set of indices as range(start,stop,step). Slicing syntax obj[start:stop:step] passes such a slice object as the argument to the _ _getitem_ _, _ _setitem_ _, or _ _delitem_ _ method of object obj, as appropriate. It is up to obj to interpret the slice objects that its methods receive. See also "Container slicing" on page 110.
| staticmethod | staticmethod(function)
Returns a static method object. In practice, you call this built-in type only within a class body, and, most often, in Python 2.4, you use it as a decorator. See "Static methods" on page 99.
| str
| str(obj)
Returns a concise and readable string representation of obj. If obj is a string, str returns obj. See also repr on page 166 and _ _str_ _ on page 109.
| super | super(cls,obj)
Returns a super-object of object obj (which must be an instance of class cls or a subclass of cls) suitable for calling superclass methods. In practice, you call this built-in type only within a method's code. See "Cooperative superclass method calling" on page 97.
| tuple | tuple(seq)
Returns a tuple with the same items as the iterable object seq in the same order. When seq is a tuple, tuple returns seq itself, like seq[:] does. See "Tuples" on page 42.
| type | type(obj)
Returns the type object that is the type of obj (i.e., the most-derived, a.k.a. leafmost, type object of which obj is an instance). All legacy instance objects have the same type (InstanceType), even when they are instances of different classes: use isinstance (covered in "isinstance") to check whether an instance belongs to a particular class. In the new-style object model, however, type(x) is x._ _class_ _ for any x.
Checking type(x) for equality or identity to some other type object is known as type-checking. Type-checking is hardly ever appropriate in production Python code because it interferes with polymorphism. The normal idiom in Python is to try to use x as if it were of the type you expect, handling any problems with a try/except statement, as discussed in "Error-Checking Strategies" on page 134. When you just have to type-check, typically for debugging purposes, use isinstance instead. isinstance(x,atype) is a lesser evil than type(x) is atype, since at least it accepts an x that is an instance of any subclass of atype, not just a direct instance of atype itself.
| unicode | unicode(string[,codec[,errors]])
Returns the Unicode string object obtained by decoding string. codec names the codec to use. If codec is missing, unicode uses the default codec (generally 'ascii'). errors, if present, is a string that specifies how to handle decoding errors. See also "Unicode" on page 198, particularly for information about codecs and errors, and _ _unicode_ _ on page 109.
| xrange | xrange([start,]stop[,step=1])
Returns a read-only sequence object whose items are integers in arithmetic progression. The arguments are the same as for range, covered in "range". While range creates and returns a normal list object, xrange returns a sequence object of a special type, mostly meant to be used in a for statement (you can index that object, but you cannot slice it). xrange consumes less memory than range for this specific, frequent use, in which all you need to do is loop on an arithmetic progression. However, xrange has a slightly higher overhead than range for the loop itself. Overall, performance differences between xrange and range are normally small and not worth worrying about.
|
![](images/pixel.jpg) |