4.6. Standard Type Built-in Functions

Along with generic operators which we have just seen, Python also provides some built-in functions that can be applied to all the basic object types: cmp(), repr(), str(), type(), and the single reverse or back quotes ( '' ) operator, which is functionally-equivalent to repr().

Table 4.4. Standard Type Built-in Functions
functionoperation
cmp(obj1, obj2)compares obj1 and obj2, returns integer i where:

i < 0 if obj1 < obj2

i > 0 if obj1 > obj2

i == 0 if obj1 == obj2
repr(obj)/' obj'returns evaluatable string representation of obj
str(obj)returns printable string representation of obj
type(obj)determines type of obj and return type object

4.6.1. cmp()

The cmp() built-in function CoMPares two objects, say, obj1 and obj2, and returns a negative number (integer) if obj1 is less than obj2, a positive number if obj1 is greater than obj2, and zero if obj1 is equal to obj2. Notice the similarity in return values as C's strcmp(). The comparison used is the one that applies for that type of object, whether it be a standard type or a user-created class; if the latter, cmp() will call the class's special __cmp__() method. More on these special methods in Chapter 13, on Python classes. Here are some samples of using the cmp() built-in function with numbers and strings.

>>> a, b = -4, 12
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = -4
>>> cmp(a,b)
0
>>>
>>> a, b = 'abc', 'xyz'
>>> cmp(a,b)
-23
>>> cmp(b,a)
23
>>> b = 'abc'
>>> cmp(a,b)
0

We will look at using cmp() with other objects later.

4.6.2. str() and repr() (and ''Operator)

The str() STRing and repr() REPResentation built-in functions or the single back or reverse quote operator ( `` ) come in really handy if the need arises to either recreate an object through evaluation or obtain a human-readable view of the contents of objects, data values, object types, etc. To use these operations, a Python object is provided as an argument and some type of string representation of that object is returned.

In some examples below, we take some random Python types and convert them to their string representations.

>>> str(4.53-2j)
'(4.53-2j)'
>>>
>>> str(1)
'1'
>>>>>> str(2e10)
'20000000000.0'
>>>
>>> str([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> repr([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> `[0, 5, 9, 9]`
'[0, 5, 9, 9]'

Although all three are similar in nature and functionality, only repr() and `` do exactly the same thing, and using them will deliver the “official” string representation of an object that can be evaluated as a valid Python expression (using the eval() built-in function). In contrast, str() has the job of delivering a “printable” string representation of an object which may not necessarily be acceptable by eval(), but will look nice in a print statement.

The executive summary is that repr() is Python-friendly while str() produces human-friendly output. However, with that said, because both types of string representations coincide so often, on many occasions all three return the exact same string.

CORE NOTE: Why have both repr() and `` ?

Occasionally in Python, you will find both an operator and a function that do exactly the same thing. One reason why both an operator and a function exist is that there are times where a function may be more useful than the operator, for example, when you are passing around executable objects like functions and where different functions may be called depending on the data item. Another example is the double-star ( ** ) and pow() built-in function which performsx to the y powerexponentiation for x ** y or pow(x,y).


4.6.3. A Second Look at type()

Python does not support method or function overloading, so you are responsible for any “introspection” of the objects that your functions are called with. (Also see the Python FAQ 4.75.) Fortunately, we have the type() built-in function to help us with just that, introduced earlier in Section 4.3.1.

What's in a name? Quite a lot, if it is the name of a type. It is often advantageous and/or necessary to base pending computation on the type of object that is received. Fortunately, Python provides a built-in function just for that very purpose. type() returns the type for any Python object, not just the standard types. Using the interactive interpreter, let's take a look at some examples of what type() returns when we give it various objects.

>>> type('')
<type 'string'>
>>>
>>> s = 'xyz'
>>>
>>> type(s)
<type 'string'>
>>>
>>> type(100)
<type 'int'>
>>>
>>> type(-2)
<type 'int'>
>>>
>>> type(0)
<type 'int'>
>>>
>>> type(0+0j)
<type 'complex'>
>>>
>>> type(0L)
<type 'long int'>
>>>
>>> type(0.0)
<type 'float'>
>>>
>>> type([])
<type 'list'>
>>>
>>> type(())
<type 'tuple'>
>>>
>>> type({})
<type 'dictionary'>
>>>
>>> type(type)
<type 'builtin_function_or_method'>
>>>
>>> type(Abc)
<type 'class'>
>>>
>>> type(Abc_obj)
<type 'instance'>

You will find most of these types familiar, as we discussed them at the beginning of the chapter, however, you can now see how Python recognizes types with type(). Since we cannot usually “look” at a type object to reveal its value from outside the interactive interpreter, the best use of the type object is to compare it with other type objects to make this determination.

>>> type(1.2e-10+4.5e20j) == type(0+0j):
1
>>> type('this is a string') == type(''):
1
>>> type(34L) == type(0L)
1
>>> type(2.4) == type(3)
0

Although type() returns a type object rather than an integer, say, we can still use it to our advantage because we can make a direct comparison using the if statement. We present below a script in Example 4.1 that shows how we can use type() in a run-time environment.

Listing 4.1. Checking the Type (typechk.py)

The function displayNumType() takes a numeric argument and uses the type() built-in to indicate its type (or “not a number,” if that is the case).

1   #!/usr/bin/env python
2
3   def displayNumType(number):
4
5       print number, "is",
6       if type(number) == type(0):
7           print 'an integer'
8       elif type(number) == type(0L):
9           print 'a long'
10      elif type(number) == type(0.0):
11          print 'a float'
12      elif type(number) == type(0+0j):
13          print 'a complex number'
14      else:
15          print 'not a number at all!!'
16
17   displayNumType(-69)
18   displayNumType(9999999999999999999999L)
19   displayNumType(98.6)
20   displayNumType(-5.2+1.9j)
21   displayNumType('xxx')

Running typechk.py, we get the following output:

-69 is an integer
9999999999999999999999 is a long
98.6 is a float
(-5.2+1.9j) is a complex number
xxx is not a number at all!!

An alternative to comparing an object's type with a known object's type (as we did above and in the example below) is to utilize the types module which we briefly mentioned earlier in the chapter.

>>> import types
>>> aFloat = 1.69
>>> if type(aFloat) == types.FloatType:
…       print aFloat, 'is a float type'
… else:print aFloat, 'is not a float type'
…
1.69 is a float type

A summary of operators and built-in functions common to all basic Python types is given in Table 4.5. The progressing shaded groups indicate hierarchical precedence from highest-to-lowest order. Elements grouped with similar shading all have equal priority.

Table 4.5. Standard Type Operators and Built-In Functions
operator/functiondescriptionresult[a]
string representation
``string representationstring
built-in functions
cmp(obj1, obj2)compares two objectsinteger
repr(obj)string representationstring
str(obj)string representationstring
type(obj)determines object typetype object
value comparisons
<less thanBoolean
>greater thanBoolean
<=less than or equal toBoolean
>=greater than or equal toBoolean
==equal toBoolean
!=not equal toBoolean
<>not equal toBoolean
object comparisons
isthe same asBoolean
is notnot the same asBoolean
Boolean operators
notlogical negationBoolean
andlogical conjuctionBoolean
orlogical disjunctionBoolean

[a] Those results labelled as “Boolean” indicate a Boolean comparison; since Python does not have a Boolean type per se, the result returned is a plain integer with value 0 (for false) or 1 (for true).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset