Section 5.6. Built-in and Factory Functions


5.6. Built-in and Factory Functions

5.6.1. Standard Type Functions

In the last chapter, we introduced the cmp(), str(), and type() built-in functions that apply for all standard types. For numbers, these functions will compare two numbers, convert numbers into strings, and tell you a number's type, respectively. Here are some examples of using these functions:

>>> cmp(-6, 2) -1 >>> cmp(-4.333333, -2.718281828) -1 >>> cmp(0xFF, 255) 0 >>> str(0xFF) '255' >>> str(55.3e2) '5530.0' >>> type(0xFF) <type 'int'> >>> type(98765432109876543210L) <type 'long'> >>> type(2-1j) <type 'complex'>


5.6.2. Numeric Type Functions

Python currently supports different sets of built-in functions for numeric types. Some convert from one numeric type to another while others are more operational, performing some type of calculation on their numeric arguments.

Conversion Factory Functions

The int(), long(), float(), and complex() functions are used to convert from any numeric type to another. Starting in Python 1.5, these functions will also take strings and return the numerical value represented by the string. Beginning in 1.6, int() and long() accepted a base parameter (see below) for proper string conversionsit does not work for numeric type conversion.

A fifth function, bool(), was added in Python 2.2. At that time, it was used to normalize Boolean values to their integer equivalents of one and zero for true and false values. The Boolean type was added in Python 2.3, so true and false now had constant values of TRue and False (instead of one and zero). For more information on the Boolean type, see Section 5.7.1.

In addition, because of the unification of types and classes in Python 2.2, all of these built-in functions were converted into factory functions. Factory functions, introduced in Chapter 4, just means that these objects are now classes, and when you "call" them, you are just creating an instance of that class.

They will still behave in a similar way to the new Python user so it is probably something you do not have to worry about.

The following are some examples of using these functions:

>>> int(4.25555) 4 >>> long(42) 42L >>> float(4) 4.0 >>> complex(4) (4+0j) >>> >>> complex(2.4, -8) (2.4-8j) >>> >>> complex(2.3e-10, 45.3e4) (2.3e-10+453000j)


Table 5.5 summarizes the numeric type factory functions.

Table 5.5. Numeric Type Factory Functions[a]

Class (Factory Function)

Operation

bool(obj)[b]

Returns the Boolean value of obj, e.g., the value of executing obj.__nonzero__()

int(obj, base=10)

Returns integer representation of string or number obj; similar to string.atoi(); optional base argument introduced in 1.6

long(obj, base=10)

Returns long representation of string or number obj; similar to string.atol(); optional base argument introduced in 1.6

float(obj)

Returns floating point representation of string or number obj; similar to string.atof()

complex(str) or complex(real, imag=0.0)

Returns complex number representation of str, or builds one given real (and perhaps imaginary) component(s)


[a] Prior to Python 2.3, these were all built-in functions.

[b] New in Python 2.2 as built-in function, converted to factory function in 2.3.

Operational

Python has five operational built-in functions for numeric types: abs(), coerce(), divmod(), pow(), and round(). We will take a look at each and present some usage examples.

abs() returns the absolute value of the given argument. If the argument is a complex number, then math.sqrt(num .real2 + num.imag2) is returned. Here are some examples of using the abs() built-in function:

>>> abs(-1) 1 >>> abs(10.) 10.0 >>> abs(1.2-2.1j) 2.41867732449 >>> abs(0.23 - 0.78) 0.55


The coerce() function, although it technically is a numeric type conversion function, does not convert to a specific type and acts more like an operator, hence our placement of it in our operational built-ins section. In Section 5.5.1, we discussed numeric coercion and how Python performs that operation. The coerce() function is a way for the programmer to explicitly coerce a pair of numbers rather than letting the interpreter do it. This feature is particularly useful when defining operations for newly created numeric class types. coerce() just returns a tuple containing the converted pair of numbers. Here are some examples:

>>> coerce(1, 2) (1, 2) >>> >>> coerce(1.3, 134L) (1.3, 134.0) >>> >>> coerce(1, 134L) (1L, 134L) >>> >>> coerce(1j, 134L) (1j, (134+0j)) >>> >>> coerce(1.23-41j, 134L) ((1.23-41j), (134+0j))


The divmod() built-in function combines division and modulus operations into a single function call that returns the pair (quotient, remainder) as a tuple. The values returned are the same as those given for the classic division and modulus operators for integer types. For floats, the quotient returned is math.floor(num1/num2) and for complex numbers, the quotient is math.floor((num1/num2).real).

>>> divmod(10,3) (3, 1) >>> divmod(3,10) (0, 3) >>> divmod(10,2.5) (4.0, 0.0) >>> divmod(2.5,10) (0.0, 2.5) >>> divmod(2+1j, 0.5-1j) (0j, (2+1j))


Both pow() and the double star ( ** ) operator perform exponentiation; however, there are differences other than the fact that one is an operator and the other is a built-in function.

The ** operator did not appear until Python 1.5, and the pow() built-in takes an optional third parameter, a modulus argument. If provided, pow() will perform the exponentiation first, then return the result modulo the third argument. This feature is used for cryptographic applications and has better performance than pow(x,y) % z since the latter performs the calculations in Python rather than in C-like pow(x, y, z).

>>> pow(2,5) 32 >>>s >>> pow(5,2) 25 >>> pow(3.141592,2) 9.86960029446 >>> >>> pow(1+1j, 3) (-2+2j)


The round() built-in function has a syntax of round(flt,ndig=0). It normally rounds a floating point number to the nearest integral number and returns that result (still) as a float. When the optional ndig option is given, round() will round the argument to the specific number of decimal places.

>>> round(3) 3.0 >>> round(3.45) 3.0 >>> round(3.4999999) 3.0 >>> round(3.4999999, 1) 3.5 >>> import math >>> for eachNum in range(10): ...           print round(math.pi, eachNum) ... 3.0 3.1 3.14 3.142 3.1416 3.14159 3.141593 3.1415927 3.14159265 3.141592654 3.1415926536 >>> round(-3.5) -4.0 >>> round(-3.4) -3.0 >>> round(-3.49) -3.0 >>> round(-3.49, 1) -3.5


Note that the rounding performed by round() moves away from zero on the number line, i.e., round(.5) goes to 1 and round(-.5) goes to -1. Also, with functions like int(), round(), and math.floor(), all may seem like they are doing the same thing; it is possible to get them all confused. Here is how you can differentiate among these:

  • int() chops off the decimal point and everything after (aka truncation).

  • floor() rounds you to the next smaller integer, i.e., the next integer moving in a negative direction (toward the left on the number line).

  • round() (rounded zero digits) rounds you to the nearest integer period.

Here is the output for four different values, positive and negative, and the results of running these three functions on eight different numbers. (We reconverted the result from int() back to a float so that you can visualize the results more clearly when compared to the output of the other two functions.)

>>> import math >>> for eachNum in (.2, .7, 1.2, 1.7, -.2, -.7, -1.2, -1.7): ...     print "int(%.1f)\t%+.1f" % (eachNum, float(int(eachNum))) ...     print "floor(%.1f)\t%+.1f" % (eachNum, ...     math.floor(eachNum)) ...     print "round(%.1f)\t%+.1f" % (eachNum, round(eachNum)) ...     print '-' * 20 ... int(0.2)     +0.0 floor(0.2)   +0.0 round(0.2)   +0.0 -------------------- int(0.7)     +0.0 floor(0.7)   +0.0 round(0.7)   +1.0 -------------------- int(1.2)     +1.0 floor(1.2)   +1.0 round(1.2)   +1.0 -------------------- int(1.7)     +1.0 floor(1.7)   +1.0 round(1.7)   +2.0 -------------------- int(-0.2)    +0.0 floor(-0.2)  -1.0 round(-0.2)  +0.0 -------------------- int(-0.7)    +0.0 floor(-0.7)  -1.0 round(-0.7)  -1.0 -------------------- int(-1.2)    -1.0 floor(-1.2)  -2.0 round(-1.2)  -1.0 -------------------- int(-1.7)    -1.0 floor(-1.7)  -2.0 round(-1.7)  -2.0


Table 5.6 summarizes the operational functions for numeric types.

Table 5.6. Numeric Type Operational Built-in Functions[a]

Function

Operation

abs(num)

Returns the absolute value of num

coerce(num1, num2)

Converts num1 and num2 to the same numeric type and returns the converted pair as a tuple

divmod(num1, num2)

Division-modulo combination returns (num1 / num2, num1 % num2) as a tuple; for floats and complex, the quotient is rounded down (complex uses only real component of quotient)

pow(num1, num2, mod=1)

Raises num1 to num2 power, quantity modulo mod if provided

round(flt, ndig=0)

(Floats only) takes a float flt and rounds it to ndig digits, defaulting to zero if not provided


[a] Except for round(), which applies only to floats.

5.6.3. Integer-Only Functions

In addition to the built-in functions for all numeric types, Python supports a few that are specific only to integers (plain and long). These functions fall into two categories, base presentation with hex() and oct(), and ASCII conversion featuring chr() and ord().

Base Representation

As we have seen before, Python integers automatically support octal and hexadecimal representations in addition to the decimal standard. Also, Python has two built-in functions that return string representations of an integer's octal or hexadecimal equivalent. These are the oct() and hex() built-in functions, respectively. They both take an integer (in any representation) object and return a string with the corresponding value. The following are some examples of their usage:

>>> hex(255) '0xff' >>> hex(23094823l) '0x1606627L' >>> hex(65535*2) '0x1fffe' >>> >>> oct(255) '0377' >>> oct(23094823l) '0130063047L' >>> oct(65535*2) '0377776'


ASCII Conversion

Python also provides functions to go back and forth between ASCII (American Standard Code for Information Interchange) characters and their ordinal integer values. Each character is mapped to a unique number in a table numbered from 0 to 255. This number does not change for all computers using the ASCII table, providing consistency and expected program behavior across different systems. chr() takes a single-byte integer value and returns a one-character string with the equivalent ASCII character. ord() does the opposite, taking a single ASCII character in the form of a string of length one and returns the corresponding ASCII value as an integer:

>>> ord('a') 97 >>> ord('A') 65 >>> ord('0') 48 >>> chr(97) 'a' >>> chr(65L) 'A' >>> chr(48) '0'


Table 5.7 shows all built-in functions for integer types.

Table 5.7. Integer Type Built-in Functions

Function

Operation

hex(num)

Converts num to hexadecimal and returns as string

oct(num)

Converts num to octal and returns as string

chr(num)

Takes ASCII value num and returns ASCII character as string; 0 <= num <= 255 only

ord(chr)

Takes ASCII or Unicode chr (string of length 1) and returns corresponding ordinal ASCII value or Unicode code point, respectively

unichr(num)

Takes a Unicode code point value num and returns its Unicode character as a Unicode string; valid range depends on whether your Python was built as UCS-2 or UCS-4




Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net