Home > Articles

Types and Objects

This chapter is from the book

Built-in Types

Approximately two dozen types are built into the Python interpreter and grouped into a few major categories, as shown in Table 3.1. The Type Name column in the table lists the name that can be used to check for that type using isinstance() and other type-related functions. Types include familiar objects such as numbers and sequences. Others are used during program execution and are of little practical use to most programmers. The next few sections describe the most commonly used built-in types.

Table 3.1 Built-in Python Types

Type Category

Type Name

Description

None

types.NoneType

The null object None

Numbers

int

Integer

 

long

Arbitrary-precision integer

 

float

Floating point

 

complex

Complex number

 

bool

Boolean (True or False)

Sequences

str

Character string

 

unicode

Unicode character string

 

basestring

Abstract base type for all strings

 

list

List

 

tuple

Tuple

 

xrange

Returned by xrange()

Mapping

dict

Dictionary

Sets

set

Mutable set

 

frozenset

Immutable set

Callable

types.BuiltinFunctionType

Built-in functions

 

types.BuiltinMethodType

Built-in methods

 

type

Type of built-in types and classes

 

object

Ancestor of all types and classes

 

types.FunctionType

User-defined function

 

types.InstanceType

Class object instance

 

types.MethodType

Bound class method

 

types.UnboundMethodType

Unbound class method

Modules

types.ModuleType

Module

Classes

object

Ancestor of all types and classes

Types

type

Type of built-in types and classes

Files

file

File

Internal

types.CodeType

Byte-compiled code

 

types.FrameType

Execution frame

 

types.GeneratorType

Generator object

 

types.TracebackType

Stacks traceback of an exception

 

types.SliceType

Generated by extended slices

 

types.EllipsisType

Used in extended slices

Classic Classes

types.ClassType

Old-style class definition

 

types.InstanceType

Old-style class instance

Note that object and type appear twice in Table 3.1 because classes and types are both callable. The types listed for "Classic Classes" refer to an obsolete, but still supported object-oriented interface. More details about this can be found later in this chapter and in Chapter 7, "Classes and Object-Oriented Programming."

The None Type

The None type denotes a null object (an object with no value). Python provides exactly one null object, which is written as None in a program. This object is returned by functions that don’t explicitly return a value. None is frequently used as the default value of optional arguments, so that the function can detect whether the caller has actually passed a value for that argument. None has no attributes and evaluates to False in Boolean expressions.

Numeric Types

Python uses five numeric types: Booleans, integers, long integers, floating-point numbers, and complex numbers. Except for Booleans, all numeric objects are signed. All numeric types are immutable.

Booleans are represented by two values: True and False. The names True and False are respectively mapped to the numerical values of 1 and 0.

Integers represent whole numbers in the range of –2147483648 to 2147483647 (the range may be larger on some machines). Internally, integers are stored as 2’s complement binary values, in 32 or more bits. Long integers represent whole numbers of unlimited range (limited only by available memory). Although there are two integer types, Python tries to make the distinction seamless. Most functions and operators that expect integers work with any integer type. Moreover, if the result of a numerical operation exceeds the allowed range of integer values, the result is transparently promoted to a long integer (although in certain cases, an OverflowError exception may be raised instead).

Floating-point numbers are represented using the native double-precision (64-bit) representation of floating-point numbers on the machine. Normally this is IEEE 754, which provides approximately 17 digits of precision and an exponent in the range of –308 to 308. This is the same as the double type in C. Python doesn’t support 32-bit single-precision floating-point numbers. If space and precision are an issue in your program, consider using Numerical Python (http://numpy.sourceforge.net).

Complex numbers are represented as a pair of floating-point numbers. The real and imaginary parts of a complex number z are available in z.real and z.imag.

Sequence Types

Sequences represent ordered sets of objects indexed by nonnegative integers and include strings, Unicode strings, lists, and tuples. Strings are sequences of characters, and lists and tuples are sequences of arbitrary Python objects. Strings and tuples are immutable; lists allow insertion, deletion, and substitution of elements. All sequences support iteration.

Table 3.2 shows the operators and methods that you can apply to all sequence types. Element i of sequence s is selected using the indexing operator s[i], and subsequences are selected using the slicing operator s[i:j] or extended slicing operator s[i:j:stride] (these operations are described in Chapter 4). The length of any sequence is returned using the built-in len(s) function. You can find the minimum and maximum values of a sequence by using the built-in min(s) and max(s) functions. However, these functions only work for sequences in which the elements can be ordered (typically numbers and strings).

Table 3.3 shows the additional operators that can be applied to mutable sequences such as lists.

Table 3.2 Operations and Methods Applicable to All Sequences

Item

Description

s[i]

Returns element i of a sequence

s[i:j]

Returns a slice

s[i:j:stride]

Returns an extended slice

len(s)

Number of elements in s

min(s)

Minimum value in s

max(s)

Maximum value in s

Table 3.3 Operations Applicable to Mutable Sequences

Item

Description

s[i] = v

Item assignment

s[i:j] = t

Slice assignment

s[i:j:stride] = t

Extended slice assignment

del s[i]

Item deletion

del s[i:j]

Slice deletion

del s[i:j:stride]

Extended slice deletion

Additionally, lists support the methods shown in Table 3.4. The built-in function list(s) converts any iterable type to a list. If s is already a list, this function constructs a new list that’s a shallow copy of s. The s.append(x) method appends a new element, x, to the end of the list. The s.index(x) method searches the list for the first occurrence of x. If no such element is found, a ValueError exception is raised. Similarly, the s.remove(x) method removes the first occurrence of x from the list. The s.extend(t) method extends the list s by appending the elements in sequence t. The s.sort() method sorts the elements of a list and optionally accepts a comparison function, key function, and reverse flag. The comparison function should take two arguments and return negative, zero, or positive, depending on whether the first argument is smaller, equal to, or larger than the second argument, respectively. The key function is a function that is applied to each element prior to comparison during sorting. Specifying a key function is useful if you want to perform special kinds of sorting operations, such as sorting a list of strings, but with case insensitivity. The s.reverse() method reverses the order of the items in the list. Both the sort() and reverse() methods operate on the list elements in place and return None.

Table 3.4 List Methods

Method

Description

list(s)

Converts s to a list.

s.append(x)

Appends a new element, x, to the end of s.

s.extend(t)

Appends a new list, t, to the end of s.

s.count(x)

Counts occurrences of x in s.

s.index(x [,start [,stop]])

Returns the smallest i where s[i] ==x. start and stop optionally specify the starting and ending index for the search.

s.insert(i,x)

Inserts x at index i.

s.pop([i])

Returns the element i and removes it from the list. If i is omitted, the last element is returned.

s.remove(x)

Searches for x and removes it from s.

s.reverse()

Reverses items of s in place.

s.sort([cmpfunc [, keyf [, reverse]]])

Sorts items of s in place. cmpfunc is a comparison function. keyf is a key function. reverse is a flag that sorts the list in reverse order.

Python provides two string object types. Standard strings are sequences of bytes containing 8-bit data. They may contain binary data and embedded NULL bytes. Unicode strings are sequences of 16-bit characters encoded in a format known as UCS-2. This allows for 65,536 unique character values. Although the latest Unicode standard supports up to 1 million unique character values, these extra characters are not supported by Python by default. Instead, they must be encoded as a special two-character (4-byte) sequence known as a surrogate pair—the interpretation of which is up to the application. Python does not check data for Unicode compliance or the proper use of surrogates. As an optional feature, Python may be built to store Unicode strings using 32-bit integers (UCS-4). When enabled, this allows Python to represent the entire range of Unicode values from U+000000 to U+110000. All Unicode-related functions are adjusted accordingly.

Both standard and Unicode strings support the methods shown in Table 3.5. Although these methods operate on string instances, none of these methods actually modifies the underlying string data. Thus, methods such as s.capitalize(),s.center(), and s.expandtabs() always return a new string as opposed to modifying the string s. Character tests such as s.isalnum() and s.isupper() return True or False if all the characters in the string s satisfy the test. Furthermore, these tests always return False if the length of the string is zero. The s.find(), s.index(), s.rfind(), and s.rindex() methods are used to search s for a substring. All these functions return an integer index to the substring in s. In addition, the find() method returns -1 if the substring isn’t found, whereas the index() method raises a ValueError exception. Many of the string methods accept optional start and end parameters, which are integer values specifying the starting and ending indices in s. In most cases, these values may given negative values, in which case the index is taken from the end of the string. The s.translate() method is used to perform character substitutions. The s.encode() and s.decode() methods are used to transform the string data to and from a specified character encoding. As input it accepts an encoding name such as ascii, utf-8, or utf-16. This method is most commonly used to convert Unicode strings into a data encoding suitable for I/O operations and is described further in Chapter 9, "Input and Output." More details about string methods can be found in the documentation for the string module.

Table 3.5 String Methods

Method

Description

s.capitalize()

Capitalizes the first character.

s.center(width [, pad])

Centers the string in a field of length width. pad is a padding character.

s.count(sub [,start [,end]])

Counts occurrences of the specified substring sub.

s.decode([encoding [,errors]])

Decodes a string and returns a Unicode string.

s.encode([encoding [,errors]])

Returns an encoded version of the string.

s.endswith(suffix [,start [,end]])

Checks the end of the string for a suffix.

s.expandtabs([tabsize])

Replaces tabs with spaces.

s.find(sub [, start [,end]])

Finds the first occurrence of the specified substring sub.

s.index(sub [, start [,end]])

Finds the first occurrence or error in the specified substring sub.

s.isalnum()

Checks whether all characters are alphanumeric.

s.isalpha()

Checks whether all characters are alphabetic.

s.isdigit()

Checks whether all characters are digits.

s.islower()

Checks whether all characters are lowercase.

s.isspace()

Checks whether all characters are whitespace.

s.istitle()

Checks whether the string is a title-cased string (first letter of each word capitalized).

s.isupper()

Checks whether all characters are uppercase.

s.join(t)

Joins the strings s and t.

s.ljust(width [, fill])

Left-aligns s in a string of size width.

s.lower()

Converts to lowercase.

s.lstrip([chrs])

Removes leading whitespace or characters supplied in chrs.

s.replace(old, new [,maxreplace])

Replaces the substring.

s.rfind(sub [,start [,end]])

Finds the last occurrence of a substring.

s.rindex(sub [,start [,end]])

Finds the last occurrence or raises an error.

s.rjust(width [, fill])

Right-aligns s in a string of length width.

s.rsplit([sep [,maxsplit]])

Splits a string from the end of the string using sep as a delimiter. maxsplit is the maximum number of splits to perform. If maxsplit is omitted, the result is identical to the split() method.

s.rstrip([chrs])

Removes trailing whitespace or characters supplied in chrs.

s.split([sep [,maxsplit]])

Splits a string using sep as a delimiter. maxsplit is the maximum number of splits to perform.

s.splitlines([keepends])

Splits a string into a list of lines. If keepends is 1, trailing newlines are preserved.

s.startswith(prefix [,start [,end]])

Checks whether a string starts with prefix.

s.strip([chrs])

Removes leading and trailing whitespace or characters supplied in chrs.

s.swapcase()

Converts uppercase to lowercase, and vice versa.

s.title()

Returns a title-cased version of the string.

s.translate(table [,deletechars])

Translates a string using a character translation table table, removing characters in deletechars.

s.upper()

Converts a string to uppercase.

s.zill(width)

Pads a string with zeros on the left up to the specified width.

Because there are two different string types, Python provides an abstract type, basestring, that can be used to test if an object is any kind of string. Here’s an example:

if isinstance(s,basestring):
  print "is some kind of string"

The built-in function range([i,]j [,stride]) constructs a list and populates it with integers k such that i <= k < j. The first index, i, and the stride are optional and have default values of 0 and 1, respectively. The built-in xrange([i,] j [,stride]) function performs a similar operation, but returns an immutable sequence of type xrange. Rather than storing all the values in a list, this sequence calculates its values whenever it’s accessed. Consequently, it’s much more memory-efficient when working with large sequences of integers. However, the xrange type is much more limited than its list counterpart. For example, none of the standard slicing operations are supported. This limits the utility of xrange to only a few applications such as iterating in simple loops. The xrange type provides a single method, s.tolist(), that converts its values to a list.

Mapping Types

A mapping object represents an arbitrary collection of objects that are indexed by another collection of nearly arbitrary key values. Unlike a sequence, a mapping object is unordered and can be indexed by numbers, strings, and other objects. Mappings are mutable.

Dictionaries are the only built-in mapping type and are Python’s version of a hash table or associative array. You can use any immutable object as a dictionary key value (strings, numbers, tuples, and so on). Lists, dictionaries, and tuples containing mutable objects cannot be used as keys (the dictionary type requires key values to remain constant).

To select an item in a mapping object, use the key index operator m[k], where k is a key value. If the key is not found, a KeyError exception is raised. The len(m) function returns the number of items contained in a mapping object. Table 3.6 lists the methods and operations.

Table 3.6 Methods and Operations for Dictionaries

Item

Description

len(m)

Returns the number of items in m.

m[k]

Returns the item of m with key k.

m[k]=x

Sets m[k] to x.

del m[k]

Removes m[k] from m.

m.clear()

Removes all items from m.

m.copy()

Makes a shallow copy of m.

m.has_key(k)

Returns True if m has key k; otherwise, returns False.

m.items()

Returns a list of (key,value) pairs.

m.iteritems()

Returns an iterator that produces (key,value) pairs.

m.iterkeys()

Returns an iterator that produces dictionary keys.

m.itervalues()

Returns an iterator that produces dictionary values.

m.keys()

Returns a list of key values.

m.update(b)

Adds all objects from b to m.

m.values()

Returns a list of all values in m.

m.get(k [,v])

Returns m[k] if found; otherwise, returns v.

m.setdefault(k [, v])

Returns m[k] if found; otherwise, returns v and sets m[k] = v.

m.pop(k [,default])

Returns m[k] if found and removes it from m; otherwise, returns default if supplied or raises KeyError if not.

m.popitem()

Removes a random (key,value) pair from m and returns it as a tuple.

The m.clear() method removes all items. The m.copy() method makes a shallow copy of the items contained in a mapping object and places them in a new mapping object. The m.items() method returns a list containing (key,value) pairs. The m.keys() method returns a list with all the key values, and the m.values() method returns a list with all the objects. The m.update(b) method updates the current mapping object by inserting all the (key,value) pairs found in the mapping object b. The m.get(k [,v]) method retrieves an object, but allows for an optional default value, v, that’s returned if no such object exists. The m.setdefault(k [,v]) method is similar to m.get(), except that in addition to returning v if no object exists, it sets m[k] = v. If v is omitted, it defaults to None. The m.pop() method returns an item from a dictionary and removes it at the same time. The m.popitem() method is used to iteratively destroy the contents of a dictionary. The m.iteritems(), m.iterkeys(), and m.itervalues() methods return iterators that allow looping over all the dictionary items, keys, or values, respectively.

Set Types

A set is an unordered collection of unique items. Unlike sequences, sets provide no indexing or slicing operations. They are also unlike dictionaries in that there are no key values associated with the objects. In addition, the items placed into a set must be immutable. Two different set types are available: set is a mutable set, and frozenset is an immutable set. Both kinds of sets are created using a pair of built-in functions:

s = set([1,5,10,15])
f = frozenset([‘a’,37,’hello’])

Both set() and frozenset() populate the set by iterating over the supplied argument. Both kinds of sets provide the methods outlined in Table 3.7

Table 3.7 Methods and Operations for Set Types

Item

Description

len(s)

Return number of items in s.

s.copy()

Makes a shallow copy of s.

s.difference(t)

Set difference. Returns all the items in s, but not in t.

s.intersection(t)

Intersection. Returns all the items that are both in s and in t.

s.issubbset(t)

Returns True if s is a subset of t.

s.issuperset(t)

Returns True if s is a superset of t.

s.symmetric_difference(t)

Symmetric difference. Returns all the items that are in s or t, but not in both sets.

s.union(t)

Union. Returns all items in s or t.

The s.difference(t), s.intersection(t), s.symmetric_difference(t), and s.union(t) methods provide the standard mathematical operations on sets. The returned value has the same type as s (set or frozenset). The parameter t can be any Python object that supports iteration. This includes sets, lists, tuples, and strings. These set operations are also available as mathematical operators, as described further in Chapter 4.

Mutable sets (set) additionally provide the methods outlined in Table 3.8.

Table 3.8 Methods for Mutable Set Types

Item

Description

s.add(item)

Adds item to s. Has no effect if item is already in s.

s.clear()

Removes all items from s.

s.difference_update(t)

Removes all the items from s that are also in t.

s.discard(item)

Removes item from s. If item is not a member of s, nothing happens.

s.intersection_update(t)

Computes the intersection of s and t and leaves the result in s.

s.pop()

Returns an arbitrary set element and removes it from s.

s.remove(item)

Removes item from s. If item is not a member, KeyError is raised.

s.symmetric_difference_update(t)

Computes the symmetric difference of s and t and leaves the result in s.

s.update(t)

Adds all the items in t to s. t may be another set, a sequence, or any object that supports iteration.

All these operations modify the set s in place. The parameter t can be any object that supports iteration.

Callable Types

Callable types represent objects that support the function call operation. There are several flavors of objects with this property, including user-defined functions, built-in functions, instance methods, and classes.

User-defined functions are callable objects created at the module level by using the def statement, at the class level by defining a static method, or with the lambda operator. Here’s an example:

def foo(x,y):
  return x+y


class A(object):
  @staticmethod
  def foo(x,y):
    return x+y


bar = lambda x,y: x + y

A user-defined function f has the following attributes:

Attribute(s)

Description

f.__doc__ or f.func_doc

Documentation string

f.__name__ or f.func_name

Function name

f.__dict__ or f.func_dict

Dictionary containing function attributes

f.func_code

Byte-compiled code

f.func_defaults

Tuple containing the default arguments

f.func_globals

Dictionary defining the global namespace

f.func_closure

Tuple containing data related to nested scopes

Methods are functions that operate only on instances of an object. Two types of methods—instance methods and class methods—are defined inside a class definition, as shown here:

class Foo(object):
     def __init__(self):
      self.items = [ ]
     def update(self, x):
      self.items.append(x)
     @classmethod
     def whatami(cls):
      return cls

An instance method is a method that operates on an instance of an object. The instance is passed to the method as the first argument, which is called self by convention. Here’s an example:

f = Foo()
f.update(2)    # update() method is applied to the object f

A class method operates on the class itself. The class object is passed to a class method in the first argument, cls. Here’s an example:

Foo.whatami()  # Operates on the class Foo
f.whatami()    # Operates on the class of f (Foo)

A bound method object is a method that is associated with a specific object instance. Here’s an example:

a = f.update      # a is a method bound to f
b = Foo.whatami   # b is method bound to Foo (classmethod)

In this example, the objects a and b can be called just like a function. When invoked, they will automatically apply to the underlying object to which they were bound. Here’s an example:

a(4)    # Calls f.update(4)
b()     # Calls Foo.whatami()

Bound and unbound methods are no more than a thin wrapper around an ordinary function object. The following attributes are defined for method objects:

Attribute

Description

m.__doc__

Documentation string

m.__name__

Method name

m.im_class

Class in which this method was defined

m.im_func

Function object implementing the method

m.im_self

Instance associated with the method (None if unbound)

So far, this discussion has focused on functions and methods, but class objects (described shortly) are also callable. When a class is called, a new class instance is created. In addition, if the class defines an __init__() method, it’s called to initialize the newly created instance.

An object instance is also callable if it defines a special method, __call__(). If this method is defined for an instance, x, then x(args) invokes the method x.__call__(args).

The final types of callable objects are built-in functions and methods, which correspond to code written in extension modules and are usually written in C or C++. The following attributes are available for built-in methods:

Attribute

Description

b.__doc__

Documentation string

b.__name__

Function/method name

b.__self__

Instance associated with the method

For built-in functions such as len(), __self__ is set to None, indicating that the function isn’t bound to any specific object. For built-in methods such as x.append(), where x is a list object, __self__ is set to x.

Finally, it is important to note that all functions and methods are first-class objects in Python. That is, function and method objects can be freely used like any other type. For example, they can be passed as arguments, placed in lists and dictionaries, and so forth.

Classes and Types

When you define a class, the class definition normally produces an object of type type. Here’s an example:

>>> class Foo(object):
...  pass
...
>>> type(Foo)
<type ‘type’>

When an object instance is created, the type of the instance is the class that defined it. Here’s an example:

>>> f = Foo()
>>> type(f)
<class ‘__main__.Foo’>

More details about the object-oriented interface can be found in Chapter 7. However, there are a few attributes of types and instances that may be useful. If t is a type or class, then the attribute t.__name__ contains the name of the type. The attributes t.__bases__ contains a tuple of base classes. If o is an object instance, the attribute o.__class__ contains a reference to its corresponding class and the attribute o.__dict__ is a dictionary used to hold the object’s attributes.

Modules

The module type is a container that holds objects loaded with the import statement. When the statement import foo appears in a program, for example, the name foo is assigned to the corresponding module object. Modules define a namespace that’s implemented using a dictionary accessible in the attribute __dict__. Whenever an attribute of a module is referenced (using the dot operator), it’s translated into a dictionary lookup. For example, m.x is equivalent to m.__dict__["x"]. Likewise, assignment to an attribute such as m.x = y is equivalent to m.__dict__["x"] = y. The following attributes are available:

Attribute

Description

m.__dict__

Dictionary associated with the module

m.__doc__

Module documentation string

m.__name__

Name of the module

m.__file__

File from which the module was loaded

m.__path__

Fully qualified package name, defined when the module object refers to a package

Files

The file object represents an open file and is returned by the built-in open() function (as well as a number of functions in the standard library). The methods on this type include common I/O operations such as read() and write(). However, because I/O is covered in detail in Chapter 9, readers should consult that chapter for more details.

Internal Types

A number of objects used by the interpreter are exposed to the user. These include traceback objects, code objects, frame objects, generator objects, slice objects, and the Ellipsis object. It is rarely necessary to manipulate these objects directly. However, their attributes are provided in the following sections for completeness.

Code Objects

Code objects represent raw byte-compiled executable code, or bytecode, and are typically returned by the built-in compile() function. Code objects are similar to functions except that they don’t contain any context related to the namespace in which the code was defined, nor do code objects store information about default argument values. A code object, c, has the following read-only attributes:

Attribute

Description

c.co_name

Function name.

c.co_argcount

Number of positional arguments (including default values).

c.co_nlocals

Number of local variables used by the function.

c.co_varnames

Tuple containing names of local variables.

c.co_cellvars

Tuple containing names of variables referenced by nested functions.

c.co_freevars

Tuple containing names of free variables used by nested functions.

c.co_code

String representing raw bytecode.

c.co_consts

Tuple containing the literals used by the bytecode.

c.co_names

Tuple containing names used by the bytecode.

c.co_filename

Name of the file in which the code was compiled.

c.co_firstlineno

First line number of the function.

c.co_lnotab

String encoding bytecode offsets to line numbers.

c.co_stacksize

Required stack size (including local variables).

c.co_flags

Integer containing interpreter flags. Bit 2 is set if the function uses a variable number of positional arguments using "*args". Bit 3 is set if the function allows arbitrary keyword arguments using "**kwargs". All other bits are reserved.

Frame Objects

Frame objects are used to represent execution frames and most frequently occur in traceback objects (described next). A frame object, f, has the following read-only attributes:

Attribute

Description

f.f_back

Previous stack frame (toward the caller).

f.f_code

Code object being executed.

f.f_locals

Dictionary used for local variables.

f.f_globals

Dictionary used for global variables.

f.f_builtins

Dictionary used for built-in names.

f.f_restricted

Set to 1 if executing in restricted execution mode.

f.f_lineno

Line number.

f.f_lasti

Current instruction. This is an index into the bytecode string of f_code.

The following attributes can be modified (and are used by debuggers and other tools):

Attribute

Description

f.f_trace

Function called at the start of each source code line

f.f_exc_type

Most recent exception type

f.f_exc_value

Most recent exception value

f.f_exc_traceback

Most recent exception traceback

Traceback Objects

Traceback objects are created when an exception occurs and contains stack trace information. When an exception handler is entered, the stack trace can be retrieved using the sys.exc_info() function. The following read-only attributes are available in traceback objects:

Attribute

Description

t.tb_next

Next level in the stack trace (toward the execution frame where the exception occurred)

t.tb_frame

Execution frame object of the current level

t.tb_line

Line number where the exception occurred

t.tb_lasti

Instruction being executed in the current level

Generator Objects

Generator objects are created when a generator function is invoked (see Chapter 6, "Functions and Functional Programming"). A generator function is defined whenever a function makes use of the special yield keyword. The generator object serves as both an iterator and a container for information about the generator function itself. The following attributes and methods are available:

Attribute

Description

g.gi_frame

Execution frame of the generator function.

g.gi_running

Integer indicating whether or not the generator function is currently running.

g.next()

Execute the function until the next yield statement and return the value.

Slice Objects

Slice objects are used to represent slices given in extended slice syntax, such as a[i:j:stride], a[i:j, n:m], or a[..., i:j]. Slice objects are also created using the built-in slice([i,] j [,stride]) function. The following read-only attributes are available:

Attribute

Description

s.start

Lower bound of the slice; None if omitted

s.stop

Upper bound of the slice; None if omitted

s.step

Stride of the slice; None if omitted

Slice objects also provide a single method, s.indices(length). This function takes a length and returns a tuple (start,stop,stride) that indicates how the slice would be applied to a sequence of that length. For example:

s = slice(10,20)  # Slice object represents [10:20]
s.indices(100)    # Returns (10,20,1) --> [10:20]
s.indices(15)     # Returns (10,15,1) --> [10:15]

Ellipsis Object

The Ellipsis object is used to indicate the presence of an ellipsis (...) in a slice. There is a single object of this type, accessed through the built-in name Ellipsis. It has no attributes and evaluates as True. None of Python’s built-in types makes use of Ellipsis, but it may be used in third-party applications.

Classic Classes

In versions of Python prior to version 2.2, classes and objects were implemented using an entirely different mechanism that is now deprecated. For backward compatibility, however, these classes, called classic classes or old-style classes, are still supported.

The reason that classic classes are deprecated is due to their interaction with the Python type system. Classic classes do not define new data types, nor is it possible to specialize any of the built-in types such as lists or dictionaries. To overcome this limitation, Python 2.2 unified types and classes while introducing a different implementation of user-defined classes.

A classic class is created whenever an object does not inherit (directly or indirectly) from object. For example:

# A modern class
class Foo(object):
   pass


# A classic class. Note: Does not inherit from object
class Bar:
   pass

Classic classes are implemented using a dictionary that contains all the objects defined within the class and defines a namespace. References to class attributes such as c.x are translated into a dictionary lookup, c.__dict__["x"]. If an attribute isn’t found in this dictionary, the search continues in the list of base classes. This search is depth first in the order that base classes were specified in the class definition. An attribute assignment such as c.y = 5 always updates the __dict__ attribute of c, not the dictionaries of any base class.

The following attributes are defined by class objects:

Attribute

Description

c.__dict__

Dictionary associated with the class

c.__doc__

Class documentation string

c.__name__

Name of the class

c.__module__

Name of the module in which the class was defined

c.__bases__

Tuple containing base classes

A class instance is an object created by calling a class object. Each instance has its own local namespace that's implemented as a dictionary. This dictionary and the associated class object have the following attributes:

Attribute

Description

x.__dict__

Dictionary associated with an instance

x.__class__

Class to which an instance belongs

When the attribute of an object is referenced, such as in x.a, the interpreter first searches in the local dictionary for x.__dict__["a"]. If it doesn’t find the name locally, the search continues by performing a lookup on the class defined in the __class__ attribute. If no match is found, the search continues with base classes, as described earlier. If still no match is found and the object’s class defines a __getattr__() method, it’s used to perform the lookup. The assignment of attributes such as x.a = 4 always updates x.__dict__, not the dictionaries of classes or base classes.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020