< BACKMake Note | BookmarkCONTINUE >
156135250194107072078175030179198180024228156016206217188240240204172039119068198216157185

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

function

operation

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

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.

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.

NOTE

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 performs "x to the y power" exponentiation for x ** y or pow(x,y).


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.

Example 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).

 <$nopage>
001 1   #!/usr/bin/env python
002 2
003 3   def displayNumType(number):
004 4
005 5       print number, "is",
006 6       if type(number) == type(0):
007 7           print 'an integer'
008 8       elif type(number) == type(0L):
009 9           print 'a long'
010 10      elif type(number) == type(0.0):
011 11          print 'a float'
012 12      elif type(number) == type(0+0j):
013 13          print 'a complex number'
014 14      else: <$nopage>
015 15          print 'not a number at all!!'
016 16
017 17   displayNumType(-69)
018 18   displayNumType(9999999999999999999999L)
019 19   displayNumType(98.6)
020 20   displayNumType(-5.2+1.9j)
021 21   displayNumType('xxx')
022  <$nopage>

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/function

description

result[a]

string representation

``

string representation

string

built-in functions

cmp(obj1, obj2)

compares two objects

integer

repr(obj)

string representation

string

str(obj)

string representation

string

type(obj)

determines object type

type object

value comparisons

<

less than

Boolean

>

greater than

Boolean

<=

less than or equal to

Boolean

>=

greater than or equal to

Boolean

==

equal to

Boolean

!=

not equal to

Boolean

<>

not equal to

Boolean

object comparisons

is

the same as

Boolean

is not

not the same as

Boolean

Boolean operators

not

logical negation

Boolean

and

logical conjuction

Boolean

or

logical disjunction

Boolean

[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).


Last updated on 9/14/2001
Core Python Programming, © 2002 Prentice Hall PTR

< BACKMake Note | BookmarkCONTINUE >

© 2002, O'Reilly & Associates, Inc.