Logging HOWTO

Logging HOWTO¶
- Author:
Vinay Sajip <vinay_sajip at red-dove dot com>
This page contains tutorial information. For links to reference information and a logging cookbook, please see Other resources.
Basic Logging Tutorial¶
Logging is a means of tracking events that happen when some software runs. The software’s developer adds logging calls to their code to indicate that certain events have occurred. An event is described by a descriptive message which can optionally contain variable data (i.e. data that is potentially different for each occurrence of the event). Events also have an importance which the developer ascribes to the event; the importance can also be called the level or severity.
When to use logging¶
You can access logging functionality by creating a logger via logger =
getLogger(__name__)
, and then calling the logger’s debug()
,
info()
, warning()
, error()
and
critical()
methods. To determine when to use logging, and to see
which logger methods to use when, see the table below. It states, for each of a
set of common tasks, the best tool to use for that task.
Task you want to perform |
The best tool for the task |
|---|---|
Display console output for ordinary usage of a command line script or program |
|
Report events that occur during normal operation of a program (e.g. for status monitoring or fault investigation) |
A logger’s |
Issue a warning regarding a particular runtime event |
A logger’s |
Report an error regarding a particular runtime event |
Raise an exception |
Report suppression of an error without raising an exception (e.g. error handler in a long-running server process) |
A logger’s |
The logger methods are named after the level or severity of the events they are used to track. The standard levels and their applicability are described below (in increasing order of severity):
Level |
When it’s used |
|---|---|
|
Detailed information, typically of interest only when diagnosing problems. |
|
Confirmation that things are working as expected. |
|
An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
|
Due to a more serious problem, the software has not been able to perform some function. |
|
A serious error, indicating that the program itself may be unable to continue running. |
The default level is WARNING
, which means that only events of this severity and higher
will be tracked, unless the logging package is configured to do otherwise.
Events that are tracked can be handled in different ways. The simplest way of handling tracked events is to print them to the console. Another common way is to write them to a disk file.
A simple example¶
A very simple example is:
import logging
logging.warning('Watch out!') # will print a message to the console
logging.info('I told you so') # will not print anything
If you type these lines into a script and run it, you’ll see:
WARNING:root:Watch out!
printed out on the console. The INFO
message doesn’t appear because the
default level is WARNING
. The printed message includes the indication of the
level and the description of the event provided in the logging call, i.e.
‘Watch out!’. The actual output can be formatted quite flexibly if you need
that; formatting options will also be explained later.
Notice that in this example, we use functions directly on the logging
module, like logging.debug
, rather than creating a logger and calling
functions on it. These functions operate on the root logger, but can be useful
as they will call basicConfig()
for you if it has not been called yet, like in
this example. In larger programs you’ll usually want to control the logging
configuration explicitly however - so for that reason as well as others, it’s
better to create loggers and call their methods.
Logging to a file¶
A very common situation is that of recording logging events in a file, so let’s look at that next. Be sure to try the following in a newly started Python interpreter, and don’t just continue from the session described above:
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logger.debug('This message should go to the log file')
logger.info('So should this')
logger.warning('And this, too')
logger.error('And non-ASCII stuff, too, like Øresund and Malmö')
Changed in version 3.9: The encoding argument was added. In earlier Python versions, or if not
specified, the encoding used is the default value used by open()
. While
not shown in the above example, an errors argument can also now be passed,
which determines how encoding errors are handled. For available values and
the default, see the documentation for open()
.
And now if we open the file and look at what we have, we should find the log messages:
DEBUG:__main__:This message should go to the log file
INFO:__main__:So should this
WARNING:__main__:And this, too
ERROR:__main__:And non-ASCII stuff, too, like Øresund and Malmö
This example also shows how you can set the logging level which acts as the
threshold for tracking. In this case, because we set the threshold to
DEBUG
, all of the messages were printed.
If you want to set the logging level from a command-line option such as:
--log=INFO
and you have the value of the parameter passed for --log
in some variable
loglevel, you can use:
getattr(logging, loglevel.upper())
to get the value which you’ll pass to basicConfig()
via the level
argument. You may want to error check any user input value, perhaps as in the
following example:
# assuming loglevel is bound to the string value obtained from the
# command line argument. Convert to upper case to allow the user to
# specify --log=DEBUG or --log=debug
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: %s' % loglevel)
logging.basicConfig(level=numeric_level, ...)
The call to basicConfig()
should come before any calls to a logger’s
methods such as debug()
, info()
, etc. Otherwise,
that logging event may not be handled in the desired manner.
If you run the above script several times, the messages from successive runs are appended to the file example.log. If you want each run to start afresh, not remembering the messages from earlier runs, you can specify the filemode argument, by changing the call in the above example to:
logging.basicConfig(filename='example.log', filemode='w', level=logging.DEBUG)
The output will be the same as before, but the log file is no longer appended to, so the messages from earlier runs are lost.
Logging variable data¶
To log variable data, use a format string for the event description message and append the variable data as arguments. For example:
import logging
logging.warning('%s before you %s', 'Look', 'leap!')
will display:
WARNING:root:Look before you leap!
As you can see, merging of variable data into the event description message
uses the old, %-style of string formatting. This is for backwards
compatibility: the logging package pre-dates newer formatting options such as
str.format()
and string.Template
. These newer formatting
options are supported, but exploring them is outside the scope of this
tutorial: see Using particular formatting styles throughout your application for more information.
Changing the format of displayed messages¶
To change the format which is used to display messages, you need to specify the format you want to use:
import logging
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')
which would print:
DEBUG:This message should appear on the console
INFO:So should this
WARNING:And this, too
Notice that the ‘root’ which appeared in earlier examples has disappeared. For a full set of things that can appear in format strings, you can refer to the documentation for LogRecord attributes, but for simple usage, you just need the levelname (severity), message (event description, including variable data) and perhaps to display when the event occurred. This is described in the next section.
Displaying the date/time in messages¶
To display the date and time of an event, you would place ‘%(asctime)s’ in your format string:
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
logging.warning('is when this event was logged.')
which should print something like this:
2010-12-12 11:41:42,612 is when this event was logged.
The default format for date/time display (shown above) is like ISO8601 or
RFC 3339. If you need more control over the formatting of the date/time, provide
a datefmt argument to basicConfig
, as in this example:
import logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
which would display something like this:
12/12/2010 11:46:36 AM is when this event was logged.
The format of the datefmt argument is the same as supported by
time.strftime()
.
Next Steps¶
That concludes the basic tutorial. It should be enough to get you up and running with logging. There’s a lot more that the logging package offers, but to get the best out of it, you’ll need to invest a little more of your time in reading the following sections. If you’re ready for that, grab some of your favourite beverage and carry on.
If your logging needs are simple, then use the above examples to incorporate logging into your own scripts, and if you run into problems or don’t understand something, please post a question in the Help category of the Python discussion forum and you should receive help before too long.
Still here? You can carry on reading the next few sections, which provide a slightly more advanced/in-depth tutorial than the basic one above. After that, you can take a look at the Logging Cookbook.
Advanced Logging Tutorial¶
The logging library takes a modular approach and offers several categories of components: loggers, handlers, filters, and formatters.
Loggers expose the interface that application code directly uses.
Handlers send the log records (created by loggers) to the appropriate destination.
Filters provide a finer grained facility for determining which log records to output.
Formatters specify the layout of log records in the final output.
Log event information is passed between loggers, handlers, filters and
formatters in a LogRecord
instance.
Logging is performed by calling methods on instances of the Logger
class (hereafter called loggers). Each instance has a name, and they are
conceptually arranged in a namespace hierarchy using dots (periods) as
separators. For example, a logger named ‘scan’ is the parent of loggers
‘scan.text’, ‘scan.html’ and ‘scan.pdf’. Logger names can be anything you want,
and indicate the area of an application in which a logged message originates.
A good convention to use when naming loggers is to use a module-level logger, in each module which uses logging, named as follows:
logger = logging.getLogger(__name__)
This means that logger names track the package/module hierarchy, and it’s intuitively obvious where events are logged just from the logger name.
The root of the hierarchy of loggers is called the root logger. That’s the
logger used by the functions debug()
, info()
, warning()
,
error()
and critical()
, which just call the same-named method of
the root logger. The functions and the methods have the same signatures. The
root logger’s name is printed as ‘root’ in the logged output.
It is, of course, possible to log messages to different destinations. Support is included in the package for writing log messages to files, HTTP GET/POST locations, email via SMTP, generic sockets, queues, or OS-specific logging mechanisms such as syslog or the Windows NT event log. Destinations are served by handler classes. You can create your own log destination class if you have special requirements not met by any of the built-in handler classes.
By default, no destination is set for any logging messages. You can specify
a destination (such as console or file) by using basicConfig()
as in the
tutorial examples. If you call the functions debug()
, info()
,
warning()
, error()
and critical()
, they will check to see
if no destination is set; and if one is not set, they will set a destination
of the console (sys.stderr
) and a default format for the displayed
message before delegating to the root logger to do the actual message output.
The default format set by basicConfig()
for messages is:
severity:logger name:message
You can change this by passing a format string to basicConfig()
with the
format keyword argument. For all options regarding how a format string is
constructed, see Formatter Objects.
Logging Flow¶
The flow of log event information in loggers and handlers is illustrated in the following diagram.
Loggers¶
Logger
objects have a threefold job. First, they expose several
methods to application code so that applications can log messages at runtime.
Second, logger objects determine which log messages to act upon based upon
severity (the default filtering facility) or filter objects. Third, logger
objects pass along relevant log messages to all interested log handlers.
The most widely used methods on logger objects fall into two categories: configuration and message sending.
These are the most common configuration methods:
Logger.setLevel()
specifies the lowest-severity log message a logger will handle, where debug is the lowest built-in severity level and critical is the highest built-in severity. For example, if the severity level is INFO, the logger will handle only INFO, WARNING, ERROR, and CRITICAL messages and will ignore DEBUG messages.Logger.addHandler()
andLogger.removeHandler()
add and remove handler objects from the logger object. Handlers are covered in more detail in Handlers.Logger.addFilter()
andLogger.removeFilter()
add and remove filter objects from the logger object. Filters are covered in more detail in Filter Objects.
You don’t need to always call these methods on every logger you create. See the last two paragraphs in this section.
With the logger object configured, the following methods create log messages:
Logger.debug()
,Logger.info()
,Logger.warning()
,Logger.error()
, andLogger.critical()
all create log records with a message and a level that corresponds to their respective method names. The message is actually a format string, which may contain the standard string substitution syntax of%s
,%d
,%f
, and so on. The rest of their arguments is a list of objects that correspond with the substitution fields in the message. With regard to**kwargs
, the logging methods care only about a keyword ofexc_info
and use it to determine whether to log exception information.Logger.exception()
creates a log message similar toLogger.error()
. The difference is thatLogger.exception()
dumps a stack trace along with it. Call this method only from an exception handler.Logger.log()
takes a log level as an explicit argument. This is a little more verbose for logging messages than using the log level convenience methods listed above, but this is how to log at custom log levels.
getLogger()
returns a reference to a logger instance with the specified
name if it is provided, or root
if not. The names are period-separated
hierarchical structures. Multiple calls to getLogger()
with the same name
will return a reference to the same logger object. Loggers that are further
down in the hierarchical list are children of loggers higher up in the list.
For example, given a logger with a name of foo
, loggers with names of
foo.bar
, foo.bar.baz
, and foo.bam
are all descendants of foo
.
Loggers have a concept of effective level. If a level is not explicitly set
on a logger, the level of its parent is used instead as its effective level.
If the parent has no explicit level set, its parent is examined, and so on -
all ancestors are searched until an explicitly set level is found. The root
logger always has an explicit level set (WARNING
by default). When deciding
whether to process an event, the effective level of the logger is used to
determine whether the event is passed to the logger’s handlers.
Child loggers propagate messages up to the handlers associated with their
ancestor loggers. Because of this, it is unnecessary to define and configure
handlers for all the loggers an application uses. It is sufficient to
configure handlers for a top-level logger and create child loggers as needed.
(You can, however, turn off propagation by setting the propagate
attribute of a logger to False
.)
Handlers¶
Handler
objects are responsible for dispatching the
appropriate log messages (based on the log messages’ severity) to the handler’s
specified destination. Logger
objects can add zero or more handler
objects to themselves with an addHandler()
method. As an example
scenario, an application may want to send all log messages to a log file, all
log messages of error or higher to stdout, and all messages of critical to an
email address. This scenario requires three individual handlers where each
handler is responsible for sending messages of a specific severity to a specific
location.
The standard library includes quite a few handler types (see
Useful Handlers); the tutorials use mainly StreamHandler
and
FileHandler
in its examples.
There are very few methods in a handler for application developers to concern themselves with. The only handler methods that seem relevant for application developers who are using the built-in handler objects (that is, not creating custom handlers) are the following configuration methods:
The
setLevel()
method, just as in logger objects, specifies the lowest severity that will be dispatched to the appropriate destination. Why are there twosetLevel()
methods? The level set in the logger determines which severity of messages it will pass to its handlers. The level set in each handler determines which messages that handler will send on.setFormatter()
selects a Formatter object for this handler to use.addFilter()
andremoveFilter()
respectively configure and deconfigure filter objects on handlers.
Application code should not directly instantiate and use instances of
Handler
. Instead, the Handler
class is a base class that
defines the interface that all handlers should have and establishes some
default behavior that child classes can use (or override).
Formatters¶
Formatter objects configure the final order, structure, and contents of the log
message. Unlike the base logging.Handler
class, application code may
instantiate formatter classes, although you could likely subclass the formatter
if your application needs special behavior. The constructor takes three
optional arguments – a message format string, a date format string and a style
indicator.
- logging.Formatter.__init__(fmt=None, datefmt=None, style='%')¶
If there is no message format string, the default is to use the raw message. If there is no date format string, the default date format is:
%Y-%m-%d %H:%M:%S
with the milliseconds tacked on at the end. The style
is one of '%'
,
'{'
, or '$'
. If one of these is not specified, then '%'
will be used.
If the style
is '%'
, the message format string uses
%(<dictionary key>)s
styled string substitution; the possible keys are
documented in LogRecord attributes. If the style is '{'
, the message
format string is assumed to be compatible with str.format()
(using
keyword arguments), while if the style is '$'
then the message format string
should conform to what is expected by string.Template.substitute()
.
Changed in version 3.2: Added the style
parameter.
The following message format string will log the time in a human-readable format, the severity of the message, and the contents of the message, in that order:
'%(asctime)s - %(levelname)s - %(message)s'
Formatters use a user-configurable function to convert the creation time of a
record to a tuple. By default, time.localtime()
is used; to change this
for a particular formatter instance, set the converter
attribute of the
instance to a function with the same signature as time.localtime()
or
time.gmtime()
. To change it for all formatters, for example if you want
all logging times to be shown in GMT, set the converter
attribute in the
Formatter class (to time.gmtime
for GMT display).
Configuring Logging¶
Programmers can configure logging in three ways:
Creating loggers, handlers, and formatters explicitly using Python code that calls the configuration methods listed above.
Creating a logging config file and reading it using the
fileConfig()
function.Creating a dictionary of configuration information and passing it to the
dictConfig()
function.
For the reference documentation on the last two options, see Configuration functions. The following example configures a very simple logger, a console handler, and a simple formatter using Python code:
import logging
# create logger
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
ch.setFormatter(formatter)
# add ch to logger
logger.addHandler(ch)
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
Running this module from the command line produces the following output:
$ python simple_logging_module.py
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
The following Python module creates a logger, handler, and formatter nearly identical to those in the example listed above, with the only difference being the names of the objects:
import logging
import logging.config
logging.config.fileConfig('logging.conf')
# create logger
logger = logging.getLogger('simpleExample')
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
Here is the logging.conf file:
[loggers]
keys=root,simpleExample
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
[logger_simpleExample]
level=DEBUG
handlers=consoleHandler
qualname=simpleExample
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
The output is nearly identical to that of the non-config-file-based example:
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
You can see that the config file approach has a few advantages over the Python code approach, mainly separation of configuration and code and the ability of noncoders to easily modify the logging properties.
Warning
The fileConfig()
function takes a default parameter,
disable_existing_loggers
, which defaults to True
for reasons of
backward compatibility. This may or may not be what you want, since it
will cause any non-root loggers existing before the fileConfig()
call to be disabled unless they (or an ancestor) are explicitly named in
the configuration. Please refer to the reference documentation for more
information, and specify False
for this parameter if you wish.
The dictionary passed to dictConfig()
can also specify a Boolean
value with key disable_existing_loggers
, which if not specified
explicitly in the dictionary also defaults to being interpreted as
True
. This leads to the logger-disabling behaviour described above,
which may not be what you want - in which case, provide the key
explicitly with a value of False
.
Note that the class names referenced in config files need to be either relative
to the logging module, or absolute values which can be resolved using normal
import mechanisms. Thus, you could use either
WatchedFileHandler
(relative to the logging module) or
mypackage.mymodule.MyHandler
(for a class defined in package mypackage
and module mymodule
, where mypackage
is available on the Python import
path).
In Python 3.2, a new means of configuring logging has been introduced, using dictionaries to hold configuration information. This provides a superset of the functionality of the config-file-based approach outlined above, and is the recommended configuration method for new applications and deployments. Because a Python dictionary is used to hold configuration information, and since you can populate that dictionary using different means, you have more options for configuration. For example, you can use a configuration file in JSON format, or, if you have access to YAML processing functionality, a file in YAML format, to populate the configuration dictionary. Or, of course, you can construct the dictionary in Python code, receive it in pickled form over a socket, or use whatever approach makes sense for your application.
Here’s an example of the same configuration as above, in YAML format for the new dictionary-based approach:
version: 1
formatters:
simple:
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
loggers:
simpleExample:
level: DEBUG
handlers: [console]
propagate: no
root:
level: DEBUG
handlers: [console]
For more information about logging using a dictionary, see Configuration functions.
What happens if no configuration is provided¶
If no logging configuration is provided, it is possible to have a situation where a logging event needs to be output, but no handlers can be found to output the event.
The event is output using a ‘handler of last resort’, stored in
lastResort
. This internal handler is not associated with any
logger, and acts like a StreamHandler
which writes the
event description message to the current value of sys.stderr
(therefore
respecting any redirections which may be in effect). No formatting is
done on the message - just the bare event description message is printed.
The handler’s level is set to WARNING
, so all events at this and
greater severities will be output.
Changed in version 3.2: For versions of Python prior to 3.2, the behaviour is as follows:
If
raiseExceptions
isFalse
(production mode), the event is silently dropped.If
raiseExceptions
isTrue
(development mode), a message ‘No handlers could be found for logger X.Y.Z’ is printed once.
To obtain the pre-3.2 behaviour,
lastResort
can be set to None
.
Configuring Logging for a Library¶
When developing a library which uses logging, you should take care to
document how the library uses logging - for example, the names of loggers
used. Some consideration also needs to be given to its logging configuration.
If the using application does not use logging, and library code makes logging
calls, then (as described in the previous section) events of severity
WARNING
and greater will be printed to sys.stderr
. This is regarded as
the best default behaviour.
If for some reason you don’t want these messages printed in the absence of any logging configuration, you can attach a do-nothing handler to the top-level logger for your library. This avoids the message being printed, since a handler will always be found for the library’s events: it just doesn’t produce any output. If the library user configures logging for application use, presumably that configuration will add some handlers, and if levels are suitably configured then logging calls made in library code will send output to those handlers, as normal.
A do-nothing handler is included in the logging package:
NullHandler
(since Python 3.1). An instance of this handler
could be added to the top-level logger of the logging namespace used by the
library (if you want to prevent your library’s logged events being output to
sys.stderr
in the absence of logging configuration). If all logging by a
library foo is done using loggers with names matching ‘foo.x’, ‘foo.x.y’,
etc. then the code:
import logging
logging.getLogger('foo').addHandler(logging.NullHandler())
should have the desired effect. If an organisation produces a number of libraries, then the logger name specified can be ‘orgname.foo’ rather than just ‘foo’.
Note
It is strongly advised that you do not log to the root logger
in your library. Instead, use a logger with a unique and easily
identifiable name, such as the __name__
for your library’s top-level package
or module. Logging to the root logger will make it difficult or impossible for
the application developer to configure the logging verbosity or handlers of
your library as they wish.
Note
It is strongly advised that you do not add any handlers other
than NullHandler
to your library’s loggers. This is
because the configuration of handlers is the prerogative of the application
developer who uses your library. The application developer knows their
target audience and what handlers are most appropriate for their
application: if you add handlers ‘under the hood’, you might well interfere
with their ability to carry out unit tests and deliver logs which suit their
requirements.
Logging Levels¶
The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost.
Level |
Numeric value |
|---|---|
|
50 |
|
40 |
|
30 |
|
20 |
|
10 |
|
0 |
Levels can also be associated with loggers, being set either by the developer or through loading a saved logging configuration. When a logging method is called on a logger, the logger compares its own level with the level associated with the method call. If the logger’s level is higher than the method call’s, no logging message is actually generated. This is the basic mechanism controlling the verbosity of logging output.
Logging messages are encoded as instances of the LogRecord
class. When a logger decides to actually log an event, a
LogRecord
instance is created from the logging message.
Logging messages are subjected to a dispatch mechanism through the use of
handlers, which are instances of subclasses of the Handler
class. Handlers are responsible for ensuring that a logged message (in the form
of a LogRecord
) ends up in a particular location (or set of locations)
which is useful for the target audience for that message (such as end users,
support desk staff, system administrators, developers). Handlers are passed
LogRecord
instances intended for particular destinations. Each logger
can have zero, one or more handlers associated with it (via the
addHandler()
method of Logger
). In addition to any
handlers directly associated with a logger, all handlers associated with all
ancestors of the logger are called to dispatch the message (unless the
propagate flag for a logger is set to a false value, at which point the
passing to ancestor handlers stops).
Just as for loggers, handlers can have levels associated with them. A handler’s
level acts as a filter in the same way as a logger’s level does. If a handler
decides to actually dispatch an event, the emit()
method is used
to send the message to its destination. Most user-defined subclasses of
Handler
will need to override this emit()
.
Custom Levels¶
Defining your own levels is possible, but should not be necessary, as the existing levels have been chosen on the basis of practical experience. However, if you are convinced that you need custom levels, great care should be exercised when doing this, and it is possibly a very bad idea to define custom levels if you are developing a library. That’s because if multiple library authors all define their own custom levels, there is a chance that the logging output from such multiple libraries used together will be difficult for the using developer to control and/or interpret, because a given numeric value might mean different things for different libraries.
Useful Handlers¶
In addition to the base Handler
class, many useful subclasses are
provided:
StreamHandler
instances send messages to streams (file-like objects).FileHandler
instances send messages to disk files.BaseRotatingHandler
is the base class for handlers that rotate log files at a certain point. It is not meant to be instantiated directly. Instead, useRotatingFileHandler
orTimedRotatingFileHandler
.RotatingFileHandler
instances send messages to disk files, with support for maximum log file sizes and log file rotation.TimedRotatingFileHandler
instances send messages to disk files, rotating the log file at certain timed intervals.SocketHandler
instances send messages to TCP/IP sockets. Since 3.4, Unix domain sockets are also supported.DatagramHandler
instances send messages to UDP sockets. Since 3.4, Unix domain sockets are also supported.SMTPHandler
instances send messages to a designated email address.SysLogHandler
instances send messages to a Unix syslog daemon, possibly on a remote machine.NTEventLogHandler
instances send messages to a Windows NT/2000/XP event log.MemoryHandler
instances send messages to a buffer in memory, which is flushed whenever specific criteria are met.HTTPHandler
instances send messages to an HTTP server using eitherGET
orPOST
semantics.WatchedFileHandler
instances watch the file they are logging to. If the file changes, it is closed and reopened using the file name. This handler is only useful on Unix-like systems; Windows does not support the underlying mechanism used.QueueHandler
instances send messages to a queue, such as those implemented in thequeue
ormultiprocessing
modules.NullHandler
instances do nothing with error messages. They are used by library developers who want to use logging, but want to avoid the ‘No handlers could be found for logger XXX’ message which can be displayed if the library user has not configured logging. See Configuring Logging for a Library for more information.
Added in version 3.1: The NullHandler
class.
Added in version 3.2: The QueueHandler
class.
The NullHandler
, StreamHandler
and FileHandler
classes are defined in the core logging package. The other handlers are
defined in a sub-module, logging.handlers
. (There is also another
sub-module, logging.config
, for configuration functionality.)
Logged messages are formatted for presentation through instances of the
Formatter
class. They are initialized with a format string suitable for
use with the % operator and a dictionary.
For formatting multiple messages in a batch, instances of
BufferingFormatter
can be used. In addition to the format
string (which is applied to each message in the batch), there is provision for
header and trailer format strings.
When filtering based on logger level and/or handler level is not enough,
instances of Filter
can be added to both Logger
and
Handler
instances (through their addFilter()
method).
Before deciding to process a message further, both loggers and handlers consult
all their filters for permission. If any filter returns a false value, the
message is not processed further.
The basic Filter
functionality allows filtering by specific logger
name. If this feature is used, messages sent to the named logger and its
children are allowed through the filter, and all others dropped.
Exceptions raised during logging¶
The logging package is designed to swallow exceptions which occur while logging in production. This is so that errors which occur while handling logging events - such as logging misconfiguration, network or other similar errors - do not cause the application using logging to terminate prematurely.
SystemExit
and KeyboardInterrupt
exceptions are never
swallowed. Other exceptions which occur during the emit()
method
of a Handler
subclass are passed to its handleError()
method.
The default implementation of handleError()
in Handler
checks to see if a module-level variable, raiseExceptions
, is set. If
set, a traceback is printed to sys.stderr
. If not set, the exception is
swallowed.
Note
The default value of raiseExceptions
is True
. This is
because during development, you typically want to be notified of any
exceptions that occur. It’s advised that you set raiseExceptions
to
False
for production usage.
Using arbitrary objects as messages¶
In the preceding sections and examples, it has been assumed that the message
passed when logging the event is a string. However, this is not the only
possibility. You can pass an arbitrary object as a message, and its
__str__()
method will be called when the logging system needs to
convert it to a string representation. In fact, if you want to, you can avoid
computing a string representation altogether - for example, the
SocketHandler
emits an event by pickling it and sending it
over the wire.
Optimization¶
Formatting of message arguments is deferred until it cannot be avoided.
However, computing the arguments passed to the logging method can also be
expensive, and you may want to avoid doing it if the logger will just throw
away your event. To decide what to do, you can call the
isEnabledFor()
method which takes a level argument and returns
true if the event would be created by the Logger for that level of call.
You can write code like this:
if logger.isEnabledFor(logging.DEBUG):
logger.debug('Message with %s, %s', expensive_func1(),
expensive_func2())
so that if the logger’s threshold is set above DEBUG
, the calls to
expensive_func1
and expensive_func2
are never made.
Note
In some cases, isEnabledFor()
can itself be more
expensive than you’d like (e.g. for deeply nested loggers where an explicit
level is only set high up in the logger hierarchy). In such cases (or if you
want to avoid calling a method in tight loops), you can cache the result of a
call to isEnabledFor()
in a local or instance variable, and use
that instead of calling the method each time. Such a cached value would only
need to be recomputed when the logging configuration changes dynamically
while the application is running (which is not all that common).
There are other optimizations which can be made for specific applications which need more precise control over what logging information is collected. Here’s a list of things you can do to avoid processing during logging which you don’t need:
What you don’t want to collect |
How to avoid collecting it |
|---|---|
Information about where calls were made from. |
Set |
Threading information. |
Set |
Current process ID ( |
Set |
Current process name when using |
Set |
Current |
Set |
Also note that the core logging module only includes the basic handlers. If
you don’t import logging.handlers
and logging.config
, they won’t
take up any memory.
Other resources¶
See also
- Module
logging
API reference for the logging module.
- Module
logging.config
Configuration API for the logging module.
- Module
logging.handlers
Useful handlers included with the logging module.


Functional Programming HOWTO

Functional Programming HOWTO¶
- Author:
A. M. Kuchling
- Release:
0.32
In this document, we’ll take a tour of Python’s features suitable for
implementing programs in a functional style. After an introduction to the
concepts of functional programming, we’ll look at language features such as
iterators and generators and relevant library modules such as
itertools
and functools
.
Introduction¶
This section explains the basic concept of functional programming; if you’re just interested in learning about Python language features, skip to the next section on Iterators.
Programming languages support decomposing problems in several different ways:
Most programming languages are procedural: programs are lists of instructions that tell the computer what to do with the program’s input. C, Pascal, and even Unix shells are procedural languages.
In declarative languages, you write a specification that describes the problem to be solved, and the language implementation figures out how to perform the computation efficiently. SQL is the declarative language you’re most likely to be familiar with; a SQL query describes the data set you want to retrieve, and the SQL engine decides whether to scan tables or use indexes, which subclauses should be performed first, etc.
Object-oriented programs manipulate collections of objects. Objects have internal state and support methods that query or modify this internal state in some way. Smalltalk and Java are object-oriented languages. C++ and Python are languages that support object-oriented programming, but don’t force the use of object-oriented features.
Functional programming decomposes a problem into a set of functions. Ideally, functions only take inputs and produce outputs, and don’t have any internal state that affects the output produced for a given input. Well-known functional languages include the ML family (Standard ML, OCaml, and other variants) and Haskell.
The designers of some computer languages choose to emphasize one particular approach to programming. This often makes it difficult to write programs that use a different approach. Other languages are multi-paradigm languages that support several different approaches. Lisp, C++, and Python are multi-paradigm; you can write programs or libraries that are largely procedural, object-oriented, or functional in all of these languages. In a large program, different sections might be written using different approaches; the GUI might be object-oriented while the processing logic is procedural or functional, for example.
In a functional program, input flows through a set of functions. Each function operates on its input and produces some output. Functional style discourages functions with side effects that modify internal state or make other changes that aren’t visible in the function’s return value. Functions that have no side effects at all are called purely functional. Avoiding side effects means not using data structures that get updated as a program runs; every function’s output must only depend on its input.
Some languages are very strict about purity and don’t even have assignment
statements such as a=3
or c = a + b
, but it’s difficult to avoid all
side effects, such as printing to the screen or writing to a disk file. Another
example is a call to the print()
or time.sleep()
function, neither
of which returns a useful value. Both are called only for their side effects
of sending some text to the screen or pausing execution for a second.
Python programs written in functional style usually won’t go to the extreme of avoiding all I/O or all assignments; instead, they’ll provide a functional-appearing interface but will use non-functional features internally. For example, the implementation of a function will still use assignments to local variables, but won’t modify global variables or have other side effects.
Functional programming can be considered the opposite of object-oriented programming. Objects are little capsules containing some internal state along with a collection of method calls that let you modify this state, and programs consist of making the right set of state changes. Functional programming wants to avoid state changes as much as possible and works with data flowing between functions. In Python you might combine the two approaches by writing functions that take and return instances representing objects in your application (e-mail messages, transactions, etc.).
Functional design may seem like an odd constraint to work under. Why should you avoid objects and side effects? There are theoretical and practical advantages to the functional style:
Formal provability.
Modularity.
Composability.
Ease of debugging and testing.
Formal provability¶
A theoretical benefit is that it’s easier to construct a mathematical proof that a functional program is correct.
For a long time researchers have been interested in finding ways to mathematically prove programs correct. This is different from testing a program on numerous inputs and concluding that its output is usually correct, or reading a program’s source code and concluding that the code looks right; the goal is instead a rigorous proof that a program produces the right result for all possible inputs.
The technique used to prove programs correct is to write down invariants, properties of the input data and of the program’s variables that are always true. For each line of code, you then show that if invariants X and Y are true before the line is executed, the slightly different invariants X’ and Y’ are true after the line is executed. This continues until you reach the end of the program, at which point the invariants should match the desired conditions on the program’s output.
Functional programming’s avoidance of assignments arose because assignments are difficult to handle with this technique; assignments can break invariants that were true before the assignment without producing any new invariants that can be propagated onward.
Unfortunately, proving programs correct is largely impractical and not relevant to Python software. Even trivial programs require proofs that are several pages long; the proof of correctness for a moderately complicated program would be enormous, and few or none of the programs you use daily (the Python interpreter, your XML parser, your web browser) could be proven correct. Even if you wrote down or generated a proof, there would then be the question of verifying the proof; maybe there’s an error in it, and you wrongly believe you’ve proved the program correct.
Modularity¶
A more practical benefit of functional programming is that it forces you to break apart your problem into small pieces. Programs are more modular as a result. It’s easier to specify and write a small function that does one thing than a large function that performs a complicated transformation. Small functions are also easier to read and to check for errors.
Ease of debugging and testing¶
Testing and debugging a functional-style program is easier.
Debugging is simplified because functions are generally small and clearly specified. When a program doesn’t work, each function is an interface point where you can check that the data are correct. You can look at the intermediate inputs and outputs to quickly isolate the function that’s responsible for a bug.
Testing is easier because each function is a potential subject for a unit test. Functions don’t depend on system state that needs to be replicated before running a test; instead you only have to synthesize the right input and then check that the output matches expectations.
Composability¶
As you work on a functional-style program, you’ll write a number of functions with varying inputs and outputs. Some of these functions will be unavoidably specialized to a particular application, but others will be useful in a wide variety of programs. For example, a function that takes a directory path and returns all the XML files in the directory, or a function that takes a filename and returns its contents, can be applied to many different situations.
Over time you’ll form a personal library of utilities. Often you’ll assemble new programs by arranging existing functions in a new configuration and writing a few functions specialized for the current task.
Iterators¶
I’ll start by looking at a Python language feature that’s an important foundation for writing functional-style programs: iterators.
An iterator is an object representing a stream of data; this object returns the
data one element at a time. A Python iterator must support a method called
__next__()
that takes no arguments and always returns the next
element of the stream. If there are no more elements in the stream,
__next__()
must raise the StopIteration
exception.
Iterators don’t have to be finite, though; it’s perfectly reasonable to write
an iterator that produces an infinite stream of data.
The built-in iter()
function takes an arbitrary object and tries to return
an iterator that will return the object’s contents or elements, raising
TypeError
if the object doesn’t support iteration. Several of Python’s
built-in data types support iteration, the most common being lists and
dictionaries. An object is called iterable if you can get an iterator
for it.
You can experiment with the iteration interface manually:
>>> L = [1, 2, 3]
>>> it = iter(L)
>>> it
<...iterator object at ...>
>>> it.__next__() # same as next(it)
1
>>> next(it)
2
>>> next(it)
3
>>> next(it)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>>
Python expects iterable objects in several different contexts, the most
important being the for
statement. In the statement for X in Y
,
Y must be an iterator or some object for which iter()
can create an
iterator. These two statements are equivalent:
for i in iter(obj):
print(i)
for i in obj:
print(i)
Iterators can be materialized as lists or tuples by using the list()
or
tuple()
constructor functions:
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> t = tuple(iterator)
>>> t
(1, 2, 3)
Sequence unpacking also supports iterators: if you know an iterator will return N elements, you can unpack them into an N-tuple:
>>> L = [1, 2, 3]
>>> iterator = iter(L)
>>> a, b, c = iterator
>>> a, b, c
(1, 2, 3)
Built-in functions such as max()
and min()
can take a single
iterator argument and will return the largest or smallest element. The "in"
and "not in"
operators also support iterators: X in iterator
is true if
X is found in the stream returned by the iterator. You’ll run into obvious
problems if the iterator is infinite; max()
, min()
will never return, and if the element X never appears in the stream, the
"in"
and "not in"
operators won’t return either.
Note that you can only go forward in an iterator; there’s no way to get the
previous element, reset the iterator, or make a copy of it. Iterator objects
can optionally provide these additional capabilities, but the iterator protocol
only specifies the __next__()
method. Functions may therefore
consume all of the iterator’s output, and if you need to do something different
with the same stream, you’ll have to create a new iterator.
Data Types That Support Iterators¶
We’ve already seen how lists and tuples support iterators. In fact, any Python sequence type, such as strings, will automatically support creation of an iterator.
Calling iter()
on a dictionary returns an iterator that will loop over the
dictionary’s keys:
>>> m = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
... 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
>>> for key in m:
... print(key, m[key])
Jan 1
Feb 2
Mar 3
Apr 4
May 5
Jun 6
Jul 7
Aug 8
Sep 9
Oct 10
Nov 11
Dec 12
Note that starting with Python 3.7, dictionary iteration order is guaranteed to be the same as the insertion order. In earlier versions, the behaviour was unspecified and could vary between implementations.
Applying iter()
to a dictionary always loops over the keys, but
dictionaries have methods that return other iterators. If you want to iterate
over values or key/value pairs, you can explicitly call the
values()
or items()
methods to get an appropriate
iterator.
The dict()
constructor can accept an iterator that returns a finite stream
of (key, value)
tuples:
>>> L = [('Italy', 'Rome'), ('France', 'Paris'), ('US', 'Washington DC')]
>>> dict(iter(L))
{'Italy': 'Rome', 'France': 'Paris', 'US': 'Washington DC'}
Files also support iteration by calling the readline()
method until there are no more lines in the file. This means you can read each
line of a file like this:
for line in file:
# do something for each line
...
Sets can take their contents from an iterable and let you iterate over the set’s elements:
>>> S = {2, 3, 5, 7, 11, 13}
>>> for i in S:
... print(i)
2
3
5
7
11
13
Generator expressions and list comprehensions¶
Two common operations on an iterator’s output are 1) performing some operation for every element, 2) selecting a subset of elements that meet some condition. For example, given a list of strings, you might want to strip off trailing whitespace from each line or extract all the strings containing a given substring.
List comprehensions and generator expressions (short form: “listcomps” and “genexps”) are a concise notation for such operations, borrowed from the functional programming language Haskell (https://www.haskell.org/). You can strip all the whitespace from a stream of strings with the following code:
>>> line_list = [' line 1\n', 'line 2 \n', ' \n', '']
>>> # Generator expression -- returns iterator
>>> stripped_iter = (line.strip() for line in line_list)
>>> # List comprehension -- returns list
>>> stripped_list = [line.strip() for line in line_list]
You can select only certain elements by adding an "if"
condition:
>>> stripped_list = [line.strip() for line in line_list
... if line != ""]
With a list comprehension, you get back a Python list; stripped_list
is a
list containing the resulting lines, not an iterator. Generator expressions
return an iterator that computes the values as necessary, not needing to
materialize all the values at once. This means that list comprehensions aren’t
useful if you’re working with iterators that return an infinite stream or a very
large amount of data. Generator expressions are preferable in these situations.
Generator expressions are surrounded by parentheses (“()”) and list comprehensions are surrounded by square brackets (“[]”). Generator expressions have the form:
( expression for expr in sequence1
if condition1
for expr2 in sequence2
if condition2
for expr3 in sequence3
...
if condition3
for exprN in sequenceN
if conditionN )
Again, for a list comprehension only the outside brackets are different (square brackets instead of parentheses).
The elements of the generated output will be the successive values of
expression
. The if
clauses are all optional; if present, expression
is only evaluated and added to the result when condition
is true.
Generator expressions always have to be written inside parentheses, but the parentheses signalling a function call also count. If you want to create an iterator that will be immediately passed to a function you can write:
obj_total = sum(obj.count for obj in list_all_objects())
The for...in
clauses contain the sequences to be iterated over. The
sequences do not have to be the same length, because they are iterated over from
left to right, not in parallel. For each element in sequence1
,
sequence2
is looped over from the beginning. sequence3
is then looped
over for each resulting pair of elements from sequence1
and sequence2
.
To put it another way, a list comprehension or generator expression is equivalent to the following Python code:
for expr1 in sequence1:
if not (condition1):
continue # Skip this element
for expr2 in sequence2:
if not (condition2):
continue # Skip this element
...
for exprN in sequenceN:
if not (conditionN):
continue # Skip this element
# Output the value of
# the expression.
This means that when there are multiple for...in
clauses but no if
clauses, the length of the resulting output will be equal to the product of the
lengths of all the sequences. If you have two lists of length 3, the output
list is 9 elements long:
>>> seq1 = 'abc'
>>> seq2 = (1, 2, 3)
>>> [(x, y) for x in seq1 for y in seq2]
[('a', 1), ('a', 2), ('a', 3),
('b', 1), ('b', 2), ('b', 3),
('c', 1), ('c', 2), ('c', 3)]
To avoid introducing an ambiguity into Python’s grammar, if expression
is
creating a tuple, it must be surrounded with parentheses. The first list
comprehension below is a syntax error, while the second one is correct:
# Syntax error
[x, y for x in seq1 for y in seq2]
# Correct
[(x, y) for x in seq1 for y in seq2]
Generators¶
Generators are a special class of functions that simplify the task of writing iterators. Regular functions compute a value and return it, but generators return an iterator that returns a stream of values.
You’re doubtless familiar with how regular function calls work in Python or C.
When you call a function, it gets a private namespace where its local variables
are created. When the function reaches a return
statement, the local
variables are destroyed and the value is returned to the caller. A later call
to the same function creates a new private namespace and a fresh set of local
variables. But, what if the local variables weren’t thrown away on exiting a
function? What if you could later resume the function where it left off? This
is what generators provide; they can be thought of as resumable functions.
Here’s the simplest example of a generator function:
>>> def generate_ints(N):
... for i in range(N):
... yield i
Any function containing a yield
keyword is a generator function;
this is detected by Python’s bytecode compiler which compiles the
function specially as a result.
When you call a generator function, it doesn’t return a single value; instead it
returns a generator object that supports the iterator protocol. On executing
the yield
expression, the generator outputs the value of i
, similar to a
return
statement. The big difference between yield
and a return
statement is that on reaching a yield
the generator’s state of execution is
suspended and local variables are preserved. On the next call to the
generator’s __next__()
method, the function will resume
executing.
Here’s a sample usage of the generate_ints()
generator:
>>> gen = generate_ints(3)
>>> gen
<generator object generate_ints at ...>
>>> next(gen)
0
>>> next(gen)
1
>>> next(gen)
2
>>> next(gen)
Traceback (most recent call last):
File "stdin", line 1, in <module>
File "stdin", line 2, in generate_ints
StopIteration
You could equally write for i in generate_ints(5)
, or a, b, c =
generate_ints(3)
.
Inside a generator function, return value
causes StopIteration(value)
to be raised from the __next__()
method. Once this happens, or
the bottom of the function is reached, the procession of values ends and the
generator cannot yield any further values.
You could achieve the effect of generators manually by writing your own class
and storing all the local variables of the generator as instance variables. For
example, returning a list of integers could be done by setting self.count
to
0, and having the __next__()
method increment self.count
and
return it.
However, for a moderately complicated generator, writing a corresponding class
can be much messier.
The test suite included with Python’s library, Lib/test/test_generators.py, contains a number of more interesting examples. Here’s one generator that implements an in-order traversal of a tree using generators recursively.
# A recursive generator that generates Tree leaves in in-order.
def inorder(t):
if t:
for x in inorder(t.left):
yield x
yield t.label
for x in inorder(t.right):
yield x
Two other examples in test_generators.py
produce solutions for the N-Queens
problem (placing N queens on an NxN chess board so that no queen threatens
another) and the Knight’s Tour (finding a route that takes a knight to every
square of an NxN chessboard without visiting any square twice).
Passing values into a generator¶
In Python 2.4 and earlier, generators only produced output. Once a generator’s code was invoked to create an iterator, there was no way to pass any new information into the function when its execution is resumed. You could hack together this ability by making the generator look at a global variable or by passing in some mutable object that callers then modify, but these approaches are messy.
In Python 2.5 there’s a simple way to pass values into a generator.
yield
became an expression, returning a value that can be assigned to
a variable or otherwise operated on:
val = (yield i)
I recommend that you always put parentheses around a yield
expression
when you’re doing something with the returned value, as in the above example.
The parentheses aren’t always necessary, but it’s easier to always add them
instead of having to remember when they’re needed.
(PEP 342 explains the exact rules, which are that a yield
-expression must
always be parenthesized except when it occurs at the top-level expression on the
right-hand side of an assignment. This means you can write val = yield i
but have to use parentheses when there’s an operation, as in val = (yield i)
+ 12
.)
Values are sent into a generator by calling its send(value)
method. This method resumes the generator’s code and the
yield
expression returns the specified value. If the regular
__next__()
method is called, the yield
returns None
.
Here’s a simple counter that increments by 1 and allows changing the value of the internal counter.
def counter(maximum):
i = 0
while i < maximum:
val = (yield i)
# If value provided, change counter
if val is not None:
i = val
else:
i += 1
And here’s an example of changing the counter:
>>> it = counter(10)
>>> next(it)
0
>>> next(it)
1
>>> it.send(8)
8
>>> next(it)
9
>>> next(it)
Traceback (most recent call last):
File "t.py", line 15, in <module>
it.next()
StopIteration
Because yield
will often be returning None
, you should always check for
this case. Don’t just use its value in expressions unless you’re sure that the
send()
method will be the only method used to resume your
generator function.
In addition to send()
, there are two other methods on
generators:
throw(value)
is used to raise an exception inside the generator; the exception is raised by theyield
expression where the generator’s execution is paused.close()
sends aGeneratorExit
exception to the generator to terminate the iteration. On receiving this exception, the generator’s code must either raiseGeneratorExit
orStopIteration
; catching the exception and doing anything else is illegal and will trigger aRuntimeError
.close()
will also be called by Python’s garbage collector when the generator is garbage-collected.If you need to run cleanup code when a
GeneratorExit
occurs, I suggest using atry: ... finally:
suite instead of catchingGeneratorExit
.
The cumulative effect of these changes is to turn generators from one-way producers of information into both producers and consumers.
Generators also become coroutines, a more generalized form of subroutines.
Subroutines are entered at one point and exited at another point (the top of the
function, and a return
statement), but coroutines can be entered, exited,
and resumed at many different points (the yield
statements).
Built-in functions¶
Let’s look in more detail at built-in functions often used with iterators.
Two of Python’s built-in functions, map()
and filter()
duplicate the
features of generator expressions:
map(f, iterA, iterB, ...)
returns an iterator over the sequencef(iterA[0], iterB[0]), f(iterA[1], iterB[1]), f(iterA[2], iterB[2]), ...
.>>> def upper(s): ... return s.upper()
>>> list(map(upper, ['sentence', 'fragment'])) ['SENTENCE', 'FRAGMENT'] >>> [upper(s) for s in ['sentence', 'fragment']] ['SENTENCE', 'FRAGMENT']
You can of course achieve the same effect with a list comprehension.
filter(predicate, iter)
returns an iterator over all the
sequence elements that meet a certain condition, and is similarly duplicated by
list comprehensions. A predicate is a function that returns the truth
value of some condition; for use with filter()
, the predicate must take a
single value.
>>> def is_even(x):
... return (x % 2) == 0
>>> list(filter(is_even, range(10)))
[0, 2, 4, 6, 8]
This can also be written as a list comprehension:
>>> list(x for x in range(10) if is_even(x))
[0, 2, 4, 6, 8]
enumerate(iter, start=0)
counts off the elements in the
iterable returning 2-tuples containing the count (from start) and
each element.
>>> for item in enumerate(['subject', 'verb', 'object']):
... print(item)
(0, 'subject')
(1, 'verb')
(2, 'object')
enumerate()
is often used when looping through a list and recording the
indexes at which certain conditions are met:
f = open('data.txt', 'r')
for i, line in enumerate(f):
if line.strip() == '':
print('Blank line at line #%i' % i)
sorted(iterable, key=None, reverse=False)
collects all the
elements of the iterable into a list, sorts the list, and returns the sorted
result. The key and reverse arguments are passed through to the
constructed list’s sort()
method.
>>> import random
>>> # Generate 8 random numbers between [0, 10000)
>>> rand_list = random.sample(range(10000), 8)
>>> rand_list
[769, 7953, 9828, 6431, 8442, 9878, 6213, 2207]
>>> sorted(rand_list)
[769, 2207, 6213, 6431, 7953, 8442, 9828, 9878]
>>> sorted(rand_list, reverse=True)
[9878, 9828, 8442, 7953, 6431, 6213, 2207, 769]
(For a more detailed discussion of sorting, see the Sorting Techniques.)
The any(iter)
and all(iter)
built-ins look at the
truth values of an iterable’s contents. any()
returns True
if any element
in the iterable is a true value, and all()
returns True
if all of the
elements are true values:
>>> any([0, 1, 0])
True
>>> any([0, 0, 0])
False
>>> any([1, 1, 1])
True
>>> all([0, 1, 0])
False
>>> all([0, 0, 0])
False
>>> all([1, 1, 1])
True
zip(iterA, iterB, ...)
takes one element from each iterable and
returns them in a tuple:
zip(['a', 'b', 'c'], (1, 2, 3)) =>
('a', 1), ('b', 2), ('c', 3)
It doesn’t construct an in-memory list and exhaust all the input iterators before returning; instead tuples are constructed and returned only if they’re requested. (The technical term for this behaviour is lazy evaluation.)
This iterator is intended to be used with iterables that are all of the same length. If the iterables are of different lengths, the resulting stream will be the same length as the shortest iterable.
zip(['a', 'b'], (1, 2, 3)) =>
('a', 1), ('b', 2)
You should avoid doing this, though, because an element may be taken from the longer iterators and discarded. This means you can’t go on to use the iterators further because you risk skipping a discarded element.
The itertools module¶
The itertools
module contains a number of commonly used iterators as well
as functions for combining several iterators. This section will introduce the
module’s contents by showing small examples.
The module’s functions fall into a few broad classes:
Functions that create a new iterator based on an existing iterator.
Functions for treating an iterator’s elements as function arguments.
Functions for selecting portions of an iterator’s output.
A function for grouping an iterator’s output.
Creating new iterators¶
itertools.count(start, step)
returns an infinite
stream of evenly spaced values. You can optionally supply the starting number,
which defaults to 0, and the interval between numbers, which defaults to 1:
itertools.count() =>
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
itertools.count(10) =>
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.count(10, 5) =>
10, 15, 20, 25, 30, 35, 40, 45, 50, 55, ...
itertools.cycle(iter)
saves a copy of the contents of
a provided iterable and returns a new iterator that returns its elements from
first to last. The new iterator will repeat these elements infinitely.
itertools.cycle([1, 2, 3, 4, 5]) =>
1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
itertools.repeat(elem, [n])
returns the provided
element n times, or returns the element endlessly if n is not provided.
itertools.repeat('abc') =>
abc, abc, abc, abc, abc, abc, abc, abc, abc, abc, ...
itertools.repeat('abc', 5) =>
abc, abc, abc, abc, abc
itertools.chain(iterA, iterB, ...)
takes an arbitrary
number of iterables as input, and returns all the elements of the first
iterator, then all the elements of the second, and so on, until all of the
iterables have been exhausted.
itertools.chain(['a', 'b', 'c'], (1, 2, 3)) =>
a, b, c, 1, 2, 3
itertools.islice(iter, [start], stop, [step])
returns
a stream that’s a slice of the iterator. With a single stop argument, it
will return the first stop elements. If you supply a starting index, you’ll
get stop-start elements, and if you supply a value for step, elements
will be skipped accordingly. Unlike Python’s string and list slicing, you can’t
use negative values for start, stop, or step.
itertools.islice(range(10), 8) =>
0, 1, 2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8) =>
2, 3, 4, 5, 6, 7
itertools.islice(range(10), 2, 8, 2) =>
2, 4, 6
itertools.tee(iter, [n])
replicates an iterator; it
returns n independent iterators that will all return the contents of the
source iterator.
If you don’t supply a value for n, the default is 2. Replicating iterators
requires saving some of the contents of the source iterator, so this can consume
significant memory if the iterator is large and one of the new iterators is
consumed more than the others.
itertools.tee( itertools.count() ) =>
iterA, iterB
where iterA ->
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
and iterB ->
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...
Calling functions on elements¶
The operator
module contains a set of functions corresponding to Python’s
operators. Some examples are operator.add(a, b)
(adds
two values), operator.ne(a, b)
(same as a != b
), and
operator.attrgetter('id')
(returns a callable that fetches the .id
attribute).
itertools.starmap(func, iter)
assumes that the
iterable will return a stream of tuples, and calls func using these tuples as
the arguments:
itertools.starmap(os.path.join,
[('/bin', 'python'), ('/usr', 'bin', 'java'),
('/usr', 'bin', 'perl'), ('/usr', 'bin', 'ruby')])
=>
/bin/python, /usr/bin/java, /usr/bin/perl, /usr/bin/ruby
Selecting elements¶
Another group of functions chooses a subset of an iterator’s elements based on a predicate.
itertools.filterfalse(predicate, iter)
is the
opposite of filter()
, returning all elements for which the predicate
returns false:
itertools.filterfalse(is_even, itertools.count()) =>
1, 3, 5, 7, 9, 11, 13, 15, ...
itertools.takewhile(predicate, iter)
returns
elements for as long as the predicate returns true. Once the predicate returns
false, the iterator will signal the end of its results.
def less_than_10(x):
return x < 10
itertools.takewhile(less_than_10, itertools.count()) =>
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
itertools.takewhile(is_even, itertools.count()) =>
0
itertools.dropwhile(predicate, iter)
discards
elements while the predicate returns true, and then returns the rest of the
iterable’s results.
itertools.dropwhile(less_than_10, itertools.count()) =>
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, ...
itertools.dropwhile(is_even, itertools.count()) =>
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
itertools.compress(data, selectors)
takes two
iterators and returns only those elements of data for which the corresponding
element of selectors is true, stopping whenever either one is exhausted:
itertools.compress([1, 2, 3, 4, 5], [True, True, False, False, True]) =>
1, 2, 5
Combinatoric functions¶
The itertools.combinations(iterable, r)
returns an iterator giving all possible r-tuple combinations of the
elements contained in iterable.
itertools.combinations([1, 2, 3, 4, 5], 2) =>
(1, 2), (1, 3), (1, 4), (1, 5),
(2, 3), (2, 4), (2, 5),
(3, 4), (3, 5),
(4, 5)
itertools.combinations([1, 2, 3, 4, 5], 3) =>
(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5),
(2, 3, 4), (2, 3, 5), (2, 4, 5),
(3, 4, 5)
The elements within each tuple remain in the same order as
iterable returned them. For example, the number 1 is always before
2, 3, 4, or 5 in the examples above. A similar function,
itertools.permutations(iterable, r=None)
,
removes this constraint on the order, returning all possible
arrangements of length r:
itertools.permutations([1, 2, 3, 4, 5], 2) =>
(1, 2), (1, 3), (1, 4), (1, 5),
(2, 1), (2, 3), (2, 4), (2, 5),
(3, 1), (3, 2), (3, 4), (3, 5),
(4, 1), (4, 2), (4, 3), (4, 5),
(5, 1), (5, 2), (5, 3), (5, 4)
itertools.permutations([1, 2, 3, 4, 5]) =>
(1, 2, 3, 4, 5), (1, 2, 3, 5, 4), (1, 2, 4, 3, 5),
...
(5, 4, 3, 2, 1)
If you don’t supply a value for r the length of the iterable is used, meaning that all the elements are permuted.
Note that these functions produce all of the possible combinations by position and don’t require that the contents of iterable are unique:
itertools.permutations('aba', 3) =>
('a', 'b', 'a'), ('a', 'a', 'b'), ('b', 'a', 'a'),
('b', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'a')
The identical tuple ('a', 'a', 'b')
occurs twice, but the two ‘a’
strings came from different positions.
The itertools.combinations_with_replacement(iterable, r)
function relaxes a different constraint: elements can be repeated
within a single tuple. Conceptually an element is selected for the
first position of each tuple and then is replaced before the second
element is selected.
itertools.combinations_with_replacement([1, 2, 3, 4, 5], 2) =>
(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
(2, 2), (2, 3), (2, 4), (2, 5),
(3, 3), (3, 4), (3, 5),
(4, 4), (4, 5),
(5, 5)
Grouping elements¶
The last function I’ll discuss, itertools.groupby(iter, key_func=None)
, is the most complicated. key_func(elem)
is a function
that can compute a key value for each element returned by the iterable. If you
don’t supply a key function, the key is simply each element itself.
groupby()
collects all the consecutive elements from the
underlying iterable that have the same key value, and returns a stream of
2-tuples containing a key value and an iterator for the elements with that key.
city_list = [('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL'),
('Anchorage', 'AK'), ('Nome', 'AK'),
('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ'),
...
]
def get_state(city_state):
return city_state[1]
itertools.groupby(city_list, get_state) =>
('AL', iterator-1),
('AK', iterator-2),
('AZ', iterator-3), ...
where
iterator-1 =>
('Decatur', 'AL'), ('Huntsville', 'AL'), ('Selma', 'AL')
iterator-2 =>
('Anchorage', 'AK'), ('Nome', 'AK')
iterator-3 =>
('Flagstaff', 'AZ'), ('Phoenix', 'AZ'), ('Tucson', 'AZ')
groupby()
assumes that the underlying iterable’s contents will
already be sorted based on the key. Note that the returned iterators also use
the underlying iterable, so you have to consume the results of iterator-1 before
requesting iterator-2 and its corresponding key.
The functools module¶
The functools
module contains some higher-order functions.
A higher-order function takes one or more functions as input and returns a
new function. The most useful tool in this module is the
functools.partial()
function.
For programs written in a functional style, you’ll sometimes want to construct
variants of existing functions that have some of the parameters filled in.
Consider a Python function f(a, b, c)
; you may wish to create a new function
g(b, c)
that’s equivalent to f(1, b, c)
; you’re filling in a value for
one of f()
’s parameters. This is called “partial function application”.
The constructor for partial()
takes the arguments
(function, arg1, arg2, ..., kwarg1=value1, kwarg2=value2)
. The resulting
object is callable, so you can just call it to invoke function
with the
filled-in arguments.
Here’s a small but realistic example:
import functools
def log(message, subsystem):
"""Write the contents of 'message' to the specified subsystem."""
print('%s: %s' % (subsystem, message))
...
server_log = functools.partial(log, subsystem='server')
server_log('Unable to open socket')
functools.reduce(func, iter, [initial_value])
cumulatively performs an operation on all the iterable’s elements and,
therefore, can’t be applied to infinite iterables. func must be a function
that takes two elements and returns a single value. functools.reduce()
takes the first two elements A and B returned by the iterator and calculates
func(A, B)
. It then requests the third element, C, calculates
func(func(A, B), C)
, combines this result with the fourth element returned,
and continues until the iterable is exhausted. If the iterable returns no
values at all, a TypeError
exception is raised. If the initial value is
supplied, it’s used as a starting point and func(initial_value, A)
is the
first calculation.
>>> import operator, functools
>>> functools.reduce(operator.concat, ['A', 'BB', 'C'])
'ABBC'
>>> functools.reduce(operator.concat, [])
Traceback (most recent call last):
...
TypeError: reduce() of empty sequence with no initial value
>>> functools.reduce(operator.mul, [1, 2, 3], 1)
6
>>> functools.reduce(operator.mul, [], 1)
1
If you use operator.add()
with functools.reduce()
, you’ll add up all the
elements of the iterable. This case is so common that there’s a special
built-in called sum()
to compute it:
>>> import functools, operator
>>> functools.reduce(operator.add, [1, 2, 3, 4], 0)
10
>>> sum([1, 2, 3, 4])
10
>>> sum([])
0
For many uses of functools.reduce()
, though, it can be clearer to just
write the obvious for
loop:
import functools
# Instead of:
product = functools.reduce(operator.mul, [1, 2, 3], 1)
# You can write:
product = 1
for i in [1, 2, 3]:
product *= i
A related function is itertools.accumulate(iterable, func=operator.add)
. It performs the same calculation, but instead of
returning only the final result, accumulate()
returns an iterator
that also yields each partial result:
itertools.accumulate([1, 2, 3, 4, 5]) =>
1, 3, 6, 10, 15
itertools.accumulate([1, 2, 3, 4, 5], operator.mul) =>
1, 2, 6, 24, 120
The operator module¶
The operator
module was mentioned earlier. It contains a set of
functions corresponding to Python’s operators. These functions are often useful
in functional-style code because they save you from writing trivial functions
that perform a single operation.
Some of the functions in this module are:
Math operations:
add()
,sub()
,mul()
,floordiv()
,abs()
, …Logical operations:
not_()
,truth()
.Bitwise operations:
and_()
,or_()
,invert()
.Comparisons:
eq()
,ne()
,lt()
,le()
,gt()
, andge()
.Object identity:
is_()
,is_not()
.
Consult the operator module’s documentation for a complete list.
Small functions and the lambda expression¶
When writing functional-style programs, you’ll often need little functions that act as predicates or that combine elements in some way.
If there’s a Python built-in or a module function that’s suitable, you don’t need to define a new function at all:
stripped_lines = [line.strip() for line in lines]
existing_files = filter(os.path.exists, file_list)
If the function you need doesn’t exist, you need to write it. One way to write
small functions is to use the lambda
expression. lambda
takes a
number of parameters and an expression combining these parameters, and creates
an anonymous function that returns the value of the expression:
adder = lambda x, y: x+y
print_assign = lambda name, value: name + '=' + str(value)
An alternative is to just use the def
statement and define a function in the
usual way:
def adder(x, y):
return x + y
def print_assign(name, value):
return name + '=' + str(value)
Which alternative is preferable? That’s a style question; my usual course is to
avoid using lambda
.
One reason for my preference is that lambda
is quite limited in the
functions it can define. The result has to be computable as a single
expression, which means you can’t have multiway if... elif... else
comparisons or try... except
statements. If you try to do too much in a
lambda
statement, you’ll end up with an overly complicated expression that’s
hard to read. Quick, what’s the following code doing?
import functools
total = functools.reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
You can figure it out, but it takes time to disentangle the expression to figure
out what’s going on. Using a short nested def
statements makes things a
little bit better:
import functools
def combine(a, b):
return 0, a[1] + b[1]
total = functools.reduce(combine, items)[1]
But it would be best of all if I had simply used a for
loop:
total = 0
for a, b in items:
total += b
Or the sum()
built-in and a generator expression:
total = sum(b for a, b in items)
Many uses of functools.reduce()
are clearer when written as for
loops.
Fredrik Lundh once suggested the following set of rules for refactoring uses of
lambda
:
Write a lambda function.
Write a comment explaining what the heck that lambda does.
Study the comment for a while, and think of a name that captures the essence of the comment.
Convert the lambda to a def statement, using that name.
Remove the comment.
I really like these rules, but you’re free to disagree about whether this lambda-free style is better.
Revision History and Acknowledgements¶
The author would like to thank the following people for offering suggestions, corrections and assistance with various drafts of this article: Ian Bicking, Nick Coghlan, Nick Efford, Raymond Hettinger, Jim Jewett, Mike Krell, Leandro Lameiro, Jussi Salmela, Collin Winter, Blake Winton.
Version 0.1: posted June 30 2006.
Version 0.11: posted July 1 2006. Typo fixes.
Version 0.2: posted July 10 2006. Merged genexp and listcomp sections into one. Typo fixes.
Version 0.21: Added more references suggested on the tutor mailing list.
Version 0.30: Adds a section on the functional
module written by Collin
Winter; adds short section on the operator module; a few other edits.
References¶
General¶
Structure and Interpretation of Computer Programs, by Harold Abelson and Gerald Jay Sussman with Julie Sussman. The book can be found at https://mitpress.mit.edu/sicp. In this classic textbook of computer science, chapters 2 and 3 discuss the use of sequences and streams to organize the data flow inside a program. The book uses Scheme for its examples, but many of the design approaches described in these chapters are applicable to functional-style Python code.
https://defmacro.org/2006/06/19/fp.html: A general introduction to functional programming that uses Java examples and has a lengthy historical introduction.
https://en.wikipedia.org/wiki/Functional_programming: General Wikipedia entry describing functional programming.
https://en.wikipedia.org/wiki/Coroutine: Entry for coroutines.
https://en.wikipedia.org/wiki/Partial_application: Entry for the concept of partial function application.
https://en.wikipedia.org/wiki/Currying: Entry for the concept of currying.
Python-specific¶
https://gnosis.cx/TPiP/: The first chapter of David Mertz’s book Text Processing in Python discusses functional programming for text processing, in the section titled “Utilizing Higher-Order Functions in Text Processing”.
Mertz also wrote a 3-part series of articles on functional programming for IBM’s DeveloperWorks site; see part 1, part 2, and part 3,
Python documentation¶
Documentation for the itertools
module.
Documentation for the functools
module.
Documentation for the operator
module.
PEP 289: “Generator Expressions”
PEP 342: “Coroutines via Enhanced Generators” describes the new generator features in Python 2.5.