Python Notes (0.14.0)

9. built-in functions

Python contains built-in functions amongst which the standard Errors and Warnings.

See also

See the section Exceptions for more information about these errors.

To obtain the entire list of built-in function, type:

dir(__builtins__)

If we ignore all the exceptions error and warnings, we have the following list:

>>> [x for x in dir(__builtins__) if 'Error' not in x and 'Warning' not in x and 'Exception' not in x]
['Ellipsis', 'False', 'KeyboardInterrupt',
 'None', 'NotImplemented', 'StopIteration',
 'SystemExit', 'True', '__debug__', '__doc__', '__import__',
'__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr',
'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits',
'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit',
'file', 'filter', 'float', 'getattr', 'globals', 'hasattr', 'hash', 'help',
'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object',
'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input',
'reduce', 'reload', 'repr', 'round', 'setattr', 'slice', 'staticmethod',
'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars',
'xrange', 'zip']

9.1. Brief overview

Most of the following functionalities are really standard and used throughout this documentation so they do not need to be describe. In some other cases, other section described them in depth. Here is a brief summary.

9.1.1. Data structures, types and boolean type

Python provides standard data structures (see Data Structures (list, dict, tuples, sets, strings)) such as dictionary with dict(), lists with list(), immutable lists known as tuple with tuple(), string with str(), sets with set() and frozen sets with frozenset() (immutable version of set).

Note that the str(): coerces data into a string and that it works on everything ! The behaviour can be overloaded in classes using __str__ method (see Classes).

If you already know what __doc__ is, consider this example:

>>> # This function has no docstring, which is empty by default
>>> def foo(data): return data*2
>>> # the docstring is empty.
>>> foo.__doc__
>>> # However, coercing with str function returns the string 'None'
>>> # so that any __doc__ can be considered as a string.

In addition, standard types are available (basestring(), int() long() float() complex() type). The boolean type provides the False, True and bool() returns True when its argument is true. Finally, there is a special type called None which is False by default.

In order to know the type of an instance, you can use the type() function:

>>> type([1, 2])
list

9.1.2. Note about assertion

  • __debug__() contains a private boolean (cannot be set) that defines the assertion behaviour. Indeed, if optimisation is on (python -O), then asserts do not raise any error. This is a good reason to avoid using assertion but exception !

9.1.3. Conversion

There are a few functions to convert a variable in hexadecimal (hex()), octal (oct()) , ordinal (ord()), string (chr()) or unicode string (unichr())

9.1.4. Simpe Maths functions

Simple mathematical functions are available: max(), min(), sum(), pow(), abs(), round(), cmp(), divmod().

The cmp() function compares two objects and returns 0 if the two objects are equal, 1 if the first object is greater than the second, -1 if the first object is less than the second object:

>>> cmp(1, 10)
-1

Sequence objects (list, tuple) can also be compared. The comparison is made using lexicographical ordering: the first 2 element are compare. If equal, the 2 next elements are compared:

>>> cmp((1,2,3),(1,4,3))
-1

If the first elements in a sequence are equal to those in a second sequence, the smaller sequence is considered to be less:

>>> cmp([1,2,3],[1,2])
1

9.1.5. Object oriented language

There are a number of builtin functions that are related to classes.

Te function callable() returns True if the object can be called, False otherwise. Classes that have the __call__ method defined are callable. See also Classes section.

You can manipulate attributes using hasattr(), getattr() setattr() and delattr() functions.

import math
hasattr(math, 'pi')

getattr(math, 'pi') # equivalent to math.pi

setattr(math, 'pi', 3.14)
getattr(math, 'pi')

delattr(math, 'pi')
hasattr(math, 'pi')

The getattr() function returns any attribute of any object:

>>> getattr({}, "clear")
<function clear>

The object() class is the most base type that should be inherited by all classes:

>>> class Simplest(object):
...    pass

You can check that a variable is an instance of a class with isinstance():

>>> s = Simplest()
>>> isinstance(s, Simplest)
True

of that a class inherits from another one with issubclass():

>>> issubclass(Simplest, object)
True

Todo

classmethod staticmethod super id, iter, property

9.1.7. functional programming

See the Programming (and Functional programming) section for an explanation of what are the map(), apply(), filter() and reduce() and zip() functions. On top of which, you can add the lambda function, which is not part of the builtin functions.

9.1.8. Iterators

Iterators are objects that can be traversed through all the elements of a collection. When you loop over a dictionary or a string or a list you use the iterator of the structure itself. For instance, if you loop over a dictionary you actaully traverse its keys:

>>> data = {"a":1,"b":2,"c":3}
>>> for key in data:
...    print key
a
b
c

Iterators have different behaviour depending on the object type. For instance, if you loop over a string, you get characters.

You can transform an object into an iterator using the iter() builtin function

>>> x = [1,2,3]
>>> ix = iter(x)
>>> ix.next()
1
>>> ix.next()
2
>>> ix.next()
3
>>> ix.next()
StopIteration:

When there is no more element to fetch, the StopIteration error is raised.

iter() can take a callable argument. For instance:

def seek_next_line(f):
    for c in iter(lambda: f.read(1),'\n'):
        pass

The iter(callable, sentinel) can be used in such a way that the callable is called until it returns the sentinel.

9.1.9. others

See Namespace and scoping rules for more information about locals(), globals() and vars() and dir().

The exit() and quit() are equivalent. You also have autocall exit() and quit() (no need for brackets). You can also use sys.exit() to specify informative error message.

The help() prints the docstring of any object.

Todo

buffer coerce, hash, intern, __import__ copyright, credits SystemExit Ellipsis KeyboardInterrupt Notimplemented StopIteration __debug__, __name__, id, len, license and

'dreload': <function IPython.lib.deepreload.reload>,
'reload': <function reload>,
'format': <function format>,
'hash': <function hash>,
'intern': <function intern>,
'iter': <function iter>,
'next': <function next>,
'memoryview': memoryview,
'enumerate': enumerate,
'repr': <function repr>,
'reversed': reversed,
'slice': slice,
'sorted': <function sorted>,

The range() and xrange() functions generates list of integers in the specified range. xrange() is the generator version of range(). See Quick Start / Tutorial for examples.

9.3. Running code programmatically

Todo

to be checked and updated.

Python provides several built-in tools to precompile and execute frequently used pieces of code.

To compile a string (could be a module, statement) into a code object use the compile() function:

compile(string, filename, mode)

so that it can be executed by the exec statement or eval().

The filename must be a valid string, in which case mode should be ‘exec’.

The mode must be ‘exec’ to compile a module, ‘single’ to compile a single (interactive) statement, or ‘eval’ to compile an expression.

The flags argument, if present, controls which future statements influence the compilation of the code.

For instance:

eval_code = compile("a=1", "<string>", 'eval')
eval(eval_code)


single_code = compile("print 1", "<string>", 'single')
eval(single_code)


exec_code = compile(""" """)
exec exec_code


>>> eval("int(3.14159)")
3

to evaluate a string or code object: eval to evaluate a string, file object or code object: exec

to execute a source-code file, use execfile():

>>> f = open("mymod.py", "w")
>>> f.write("print('hello')")
>>> f.close()
>>> execfile("mymod.py")
'hello'