doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
add_done_callback(fn)
Attaches the callable fn to the future. fn will be called, with the future as its only argument, when the future is cancelled or finishes running. Added callables are called in the order that they were added and are always called in a thread belonging to the process that added them. If the callable raises an Exception subclass, it will be logged and ignored. If the callable raises a BaseException subclass, the behavior is undefined. If the future has already completed or been cancelled, fn will be called immediately. | python.library.concurrent.futures#concurrent.futures.Future.add_done_callback |
cancel()
Attempt to cancel the call. If the call is currently being executed or finished running and cannot be cancelled then the method will return False, otherwise the call will be cancelled and the method will return True. | python.library.concurrent.futures#concurrent.futures.Future.cancel |
cancelled()
Return True if the call was successfully cancelled. | python.library.concurrent.futures#concurrent.futures.Future.cancelled |
done()
Return True if the call was successfully cancelled or finished running. | python.library.concurrent.futures#concurrent.futures.Future.done |
exception(timeout=None)
Return the exception raised by the call. If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. If the future is cancelled before completing then CancelledError will be raised. If the call completed without raising, None is returned. | python.library.concurrent.futures#concurrent.futures.Future.exception |
result(timeout=None)
Return the value returned by the call. If the call hasn’t yet completed then this method will wait up to timeout seconds. If the call hasn’t completed in timeout seconds, then a concurrent.futures.TimeoutError will be raised. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. If the future is cancelled before completing then CancelledError will be raised. If the call raised, this method will raise the same exception. | python.library.concurrent.futures#concurrent.futures.Future.result |
running()
Return True if the call is currently being executed and cannot be cancelled. | python.library.concurrent.futures#concurrent.futures.Future.running |
set_exception(exception)
Sets the result of the work associated with the Future to the Exception exception. This method should only be used by Executor implementations and unit tests. Changed in version 3.8: This method raises concurrent.futures.InvalidStateError if the Future is already done. | python.library.concurrent.futures#concurrent.futures.Future.set_exception |
set_result(result)
Sets the result of the work associated with the Future to result. This method should only be used by Executor implementations and unit tests. Changed in version 3.8: This method raises concurrent.futures.InvalidStateError if the Future is already done. | python.library.concurrent.futures#concurrent.futures.Future.set_result |
set_running_or_notify_cancel()
This method should only be called by Executor implementations before executing the work associated with the Future and by unit tests. If the method returns False then the Future was cancelled, i.e. Future.cancel() was called and returned True. Any threads waiting on the Future completing (i.e. through as_completed() or wait()) will be woken up. If the method returns True then the Future was not cancelled and has been put in the running state, i.e. calls to Future.running() will return True. This method can only be called once and cannot be called after Future.set_result() or Future.set_exception() have been called. | python.library.concurrent.futures#concurrent.futures.Future.set_running_or_notify_cancel |
exception concurrent.futures.InvalidStateError
Raised when an operation is performed on a future that is not allowed in the current state. New in version 3.8. | python.library.concurrent.futures#concurrent.futures.InvalidStateError |
exception concurrent.futures.process.BrokenProcessPool
Derived from BrokenExecutor (formerly RuntimeError), this exception class is raised when one of the workers of a ProcessPoolExecutor has terminated in a non-clean fashion (for example, if it was killed from the outside). New in version 3.3. | python.library.concurrent.futures#concurrent.futures.process.BrokenProcessPool |
class concurrent.futures.ProcessPoolExecutor(max_workers=None, mp_context=None, initializer=None, initargs=())
An Executor subclass that executes calls asynchronously using a pool of at most max_workers processes. If max_workers is None or not given, it will default to the number of processors on the machine. If max_workers is less than or equal to 0, then a ValueError will be raised. On Windows, max_workers must be less than or equal to 61. If it is not then ValueError will be raised. If max_workers is None, then the default chosen will be at most 61, even if more processors are available. mp_context can be a multiprocessing context or None. It will be used to launch the workers. If mp_context is None or not given, the default multiprocessing context is used. initializer is an optional callable that is called at the start of each worker process; initargs is a tuple of arguments passed to the initializer. Should initializer raise an exception, all currently pending jobs will raise a BrokenProcessPool, as well as any attempt to submit more jobs to the pool. Changed in version 3.3: When one of the worker processes terminates abruptly, a BrokenProcessPool error is now raised. Previously, behaviour was undefined but operations on the executor or its futures would often freeze or deadlock. Changed in version 3.7: The mp_context argument was added to allow users to control the start_method for worker processes created by the pool. Added the initializer and initargs arguments. | python.library.concurrent.futures#concurrent.futures.ProcessPoolExecutor |
exception concurrent.futures.thread.BrokenThreadPool
Derived from BrokenExecutor, this exception class is raised when one of the workers of a ThreadPoolExecutor has failed initializing. New in version 3.7. | python.library.concurrent.futures#concurrent.futures.thread.BrokenThreadPool |
class concurrent.futures.ThreadPoolExecutor(max_workers=None, thread_name_prefix='', initializer=None, initargs=())
An Executor subclass that uses a pool of at most max_workers threads to execute calls asynchronously. initializer is an optional callable that is called at the start of each worker thread; initargs is a tuple of arguments passed to the initializer. Should initializer raise an exception, all currently pending jobs will raise a BrokenThreadPool, as well as any attempt to submit more jobs to the pool. Changed in version 3.5: If max_workers is None or not given, it will default to the number of processors on the machine, multiplied by 5, assuming that ThreadPoolExecutor is often used to overlap I/O instead of CPU work and the number of workers should be higher than the number of workers for ProcessPoolExecutor. New in version 3.6: The thread_name_prefix argument was added to allow users to control the threading.Thread names for worker threads created by the pool for easier debugging. Changed in version 3.7: Added the initializer and initargs arguments. Changed in version 3.8: Default value of max_workers is changed to min(32, os.cpu_count() + 4). This default value preserves at least 5 workers for I/O bound tasks. It utilizes at most 32 CPU cores for CPU bound tasks which release the GIL. And it avoids using very large resources implicitly on many-core machines. ThreadPoolExecutor now reuses idle worker threads before starting max_workers worker threads too. | python.library.concurrent.futures#concurrent.futures.ThreadPoolExecutor |
exception concurrent.futures.TimeoutError
Raised when a future operation exceeds the given timeout. | python.library.concurrent.futures#concurrent.futures.TimeoutError |
concurrent.futures.wait(fs, timeout=None, return_when=ALL_COMPLETED)
Wait for the Future instances (possibly created by different Executor instances) given by fs to complete. Returns a named 2-tuple of sets. The first set, named done, contains the futures that completed (finished or cancelled futures) before the wait completed. The second set, named not_done, contains the futures that did not complete (pending or running futures). timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. return_when indicates when this function should return. It must be one of the following constants:
Constant Description
FIRST_COMPLETED The function will return when any future finishes or is cancelled.
FIRST_EXCEPTION The function will return when any future finishes by raising an exception. If no future raises an exception then it is equivalent to ALL_COMPLETED.
ALL_COMPLETED The function will return when all futures finish or are cancelled. | python.library.concurrent.futures#concurrent.futures.wait |
configparser — Configuration file parser Source code: Lib/configparser.py This module provides the ConfigParser class which implements a basic configuration language which provides a structure similar to what’s found in Microsoft Windows INI files. You can use this to write Python programs which can be customized by end users easily. Note This library does not interpret or write the value-type prefixes used in the Windows Registry extended version of INI syntax. See also
Module shlex
Support for creating Unix shell-like mini-languages which can be used as an alternate format for application configuration files.
Module json
The json module implements a subset of JavaScript syntax which can also be used for this purpose. Quick Start Let’s take a very basic configuration file that looks like this: [DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
The structure of INI files is described in the following section. Essentially, the file consists of sections, each of which contains keys with values. configparser classes can read and write such files. Let’s start by creating the above configuration file programmatically. >>> import configparser
>>> config = configparser.ConfigParser()
>>> config['DEFAULT'] = {'ServerAliveInterval': '45',
... 'Compression': 'yes',
... 'CompressionLevel': '9'}
>>> config['bitbucket.org'] = {}
>>> config['bitbucket.org']['User'] = 'hg'
>>> config['topsecret.server.com'] = {}
>>> topsecret = config['topsecret.server.com']
>>> topsecret['Port'] = '50022' # mutates the parser
>>> topsecret['ForwardX11'] = 'no' # same here
>>> config['DEFAULT']['ForwardX11'] = 'yes'
>>> with open('example.ini', 'w') as configfile:
... config.write(configfile)
...
As you can see, we can treat a config parser much like a dictionary. There are differences, outlined later, but the behavior is very close to what you would expect from a dictionary. Now that we have created and saved a configuration file, let’s read it back and explore the data it holds. >>> config = configparser.ConfigParser()
>>> config.sections()
[]
>>> config.read('example.ini')
['example.ini']
>>> config.sections()
['bitbucket.org', 'topsecret.server.com']
>>> 'bitbucket.org' in config
True
>>> 'bytebong.com' in config
False
>>> config['bitbucket.org']['User']
'hg'
>>> config['DEFAULT']['Compression']
'yes'
>>> topsecret = config['topsecret.server.com']
>>> topsecret['ForwardX11']
'no'
>>> topsecret['Port']
'50022'
>>> for key in config['bitbucket.org']:
... print(key)
user
compressionlevel
serveraliveinterval
compression
forwardx11
>>> config['bitbucket.org']['ForwardX11']
'yes'
As we can see above, the API is pretty straightforward. The only bit of magic involves the DEFAULT section which provides default values for all other sections 1. Note also that keys in sections are case-insensitive and stored in lowercase 1. Supported Datatypes Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own: >>> int(topsecret['Port'])
50022
>>> float(topsecret['CompressionLevel'])
9.0
Since this task is so common, config parsers provide a range of handy getter methods to handle integers, floats and booleans. The last one is the most interesting because simply passing the value to bool() would do no good since bool('False') is still True. This is why config parsers also provide getboolean(). This method is case-insensitive and recognizes Boolean values from 'yes'/'no', 'on'/'off', 'true'/'false' and '1'/'0' 1. For example: >>> topsecret.getboolean('ForwardX11')
False
>>> config['bitbucket.org'].getboolean('ForwardX11')
True
>>> config.getboolean('bitbucket.org', 'Compression')
True
Apart from getboolean(), config parsers also provide equivalent getint() and getfloat() methods. You can register your own converters and customize the provided ones. 1 Fallback Values As with a dictionary, you can use a section’s get() method to provide fallback values: >>> topsecret.get('Port')
'50022'
>>> topsecret.get('CompressionLevel')
'9'
>>> topsecret.get('Cipher')
>>> topsecret.get('Cipher', '3des-cbc')
'3des-cbc'
Please note that default values have precedence over fallback values. For instance, in our example the 'CompressionLevel' key was specified only in the 'DEFAULT' section. If we try to get it from the section 'topsecret.server.com', we will always get the default, even if we specify a fallback: >>> topsecret.get('CompressionLevel', '3')
'9'
One more thing to be aware of is that the parser-level get() method provides a custom, more complex interface, maintained for backwards compatibility. When using this method, a fallback value can be provided via the fallback keyword-only argument: >>> config.get('bitbucket.org', 'monster',
... fallback='No such things as monsters')
'No such things as monsters'
The same fallback argument can be used with the getint(), getfloat() and getboolean() methods, for example: >>> 'BatchMode' in topsecret
False
>>> topsecret.getboolean('BatchMode', fallback=True)
True
>>> config['DEFAULT']['BatchMode'] = 'no'
>>> topsecret.getboolean('BatchMode', fallback=True)
False
Supported INI File Structure A configuration file consists of sections, each led by a [section] header, followed by key/value entries separated by a specific string (= or : by default 1). By default, section names are case sensitive but keys are not 1. Leading and trailing whitespace is removed from keys and values. Values can be omitted, in which case the key/value delimiter may also be left out. Values can also span multiple lines, as long as they are indented deeper than the first line of the value. Depending on the parser’s mode, blank lines may be treated as parts of multiline values or ignored. Configuration files may include comments, prefixed by specific characters (# and ; by default 1). Comments may appear on their own on an otherwise empty line, possibly indented. 1 For example: [Simple Values]
key=value
spaces in keys=allowed
spaces in values=allowed as well
spaces around the delimiter = obviously
you can also use : to delimit keys from values
[All Values Are Strings]
values like this: 1000000
or this: 3.14159265359
are they treated as numbers? : no
integers, floats and booleans are held as: strings
can use the API to get converted values directly: true
[Multiline Values]
chorus: I'm a lumberjack, and I'm okay
I sleep all night and I work all day
[No Values]
key_without_value
empty string value here =
[You can use comments]
# like this
; or this
# By default only in an empty line.
# Inline comments can be harmful because they prevent users
# from using the delimiting characters as parts of values.
# That being said, this can be customized.
[Sections Can Be Indented]
can_values_be_as_well = True
does_that_mean_anything_special = False
purpose = formatting for readability
multiline_values = are
handled just fine as
long as they are indented
deeper than the first line
of a value
# Did I mention we can indent comments, too?
Interpolation of values On top of the core functionality, ConfigParser supports interpolation. This means values can be preprocessed before returning them from get() calls.
class configparser.BasicInterpolation
The default implementation used by ConfigParser. It enables values to contain format strings which refer to other values in the same section, or values in the special default section 1. Additional default values can be provided on initialization. For example: [Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures
[Escape]
gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
In the example above, ConfigParser with interpolation set to BasicInterpolation() would resolve %(home_dir)s to the value of home_dir (/Users in this case). %(my_dir)s in effect would resolve to /Users/lumberjack. All interpolations are done on demand so keys used in the chain of references do not have to be specified in any specific order in the configuration file. With interpolation set to None, the parser would simply return %(my_dir)s/Pictures as the value of my_pictures and %(home_dir)s/lumberjack as the value of my_dir.
class configparser.ExtendedInterpolation
An alternative handler for interpolation which implements a more advanced syntax, used for instance in zc.buildout. Extended interpolation is using ${section:option} to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the section: part is omitted, interpolation defaults to the current section (and possibly the default values from the special section). For example, the configuration specified above with basic interpolation, would look like this with extended interpolation: [Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures
[Escape]
cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)
Values from other sections can be fetched as well: [Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python}
Mapping Protocol Access New in version 3.2. Mapping protocol access is a generic name for functionality that enables using custom objects as if they were dictionaries. In case of configparser, the mapping interface implementation is using the parser['section']['option'] notation. parser['section'] in particular returns a proxy for the section’s data in the parser. This means that the values are not copied but they are taken from the original parser on demand. What’s even more important is that when values are changed on a section proxy, they are actually mutated in the original parser. configparser objects behave as close to actual dictionaries as possible. The mapping interface is complete and adheres to the MutableMapping ABC. However, there are a few differences that should be taken into account:
By default, all keys in sections are accessible in a case-insensitive manner 1. E.g. for option in parser["section"] yields only optionxform’ed option key names. This means lowercased keys by default. At the same time, for a section that holds the key 'a', both expressions return True: "a" in parser["section"]
"A" in parser["section"]
All sections include DEFAULTSECT values as well which means that .clear() on a section may not leave the section visibly empty. This is because default values cannot be deleted from the section (because technically they are not there). If they are overridden in the section, deleting causes the default value to be visible again. Trying to delete a default value causes a KeyError.
DEFAULTSECT cannot be removed from the parser: trying to delete it raises ValueError,
parser.clear() leaves it intact,
parser.popitem() never returns it.
parser.get(section, option, **kwargs) - the second argument is not a fallback value. Note however that the section-level get() methods are compatible both with the mapping protocol and the classic configparser API.
parser.items() is compatible with the mapping protocol (returns a list of section_name, section_proxy pairs including the DEFAULTSECT). However, this method can also be invoked with arguments: parser.items(section, raw,
vars). The latter call returns a list of option, value pairs for a specified section, with all interpolations expanded (unless raw=True is provided). The mapping protocol is implemented on top of the existing legacy API so that subclasses overriding the original interface still should have mappings working as expected. Customizing Parser Behaviour There are nearly as many INI format variants as there are applications using it. configparser goes a long way to provide support for the largest sensible set of INI styles available. The default functionality is mainly dictated by historical background and it’s very likely that you will want to customize some of the features. The most common way to change the way a specific config parser works is to use the __init__() options:
defaults, default value: None This option accepts a dictionary of key-value pairs which will be initially put in the DEFAULT section. This makes for an elegant way to support concise configuration files that don’t specify values which are the same as the documented default. Hint: if you want to specify default values for a specific section, use read_dict() before you read the actual file.
dict_type, default value: dict This option has a major impact on how the mapping protocol will behave and how the written configuration files look. With the standard dictionary, every section is stored in the order they were added to the parser. Same goes for options within sections. An alternative dictionary type can be used for example to sort sections and options on write-back. Please note: there are ways to add a set of key-value pairs in a single operation. When you use a regular dictionary in those operations, the order of the keys will be ordered. For example: >>> parser = configparser.ConfigParser()
>>> parser.read_dict({'section1': {'key1': 'value1',
... 'key2': 'value2',
... 'key3': 'value3'},
... 'section2': {'keyA': 'valueA',
... 'keyB': 'valueB',
... 'keyC': 'valueC'},
... 'section3': {'foo': 'x',
... 'bar': 'y',
... 'baz': 'z'}
... })
>>> parser.sections()
['section1', 'section2', 'section3']
>>> [option for option in parser['section3']]
['foo', 'bar', 'baz']
allow_no_value, default value: False Some configuration files are known to include settings without values, but which otherwise conform to the syntax supported by configparser. The allow_no_value parameter to the constructor can be used to indicate that such values should be accepted: >>> import configparser
>>> sample_config = """
... [mysqld]
... user = mysql
... pid-file = /var/run/mysqld/mysqld.pid
... skip-external-locking
... old_passwords = 1
... skip-bdb
... # we don't need ACID today
... skip-innodb
... """
>>> config = configparser.ConfigParser(allow_no_value=True)
>>> config.read_string(sample_config)
>>> # Settings with values are treated as before:
>>> config["mysqld"]["user"]
'mysql'
>>> # Settings without values provide None:
>>> config["mysqld"]["skip-bdb"]
>>> # Settings which aren't specified still raise an error:
>>> config["mysqld"]["does-not-exist"]
Traceback (most recent call last):
...
KeyError: 'does-not-exist'
delimiters, default value: ('=', ':') Delimiters are substrings that delimit keys from values within a section. The first occurrence of a delimiting substring on a line is considered a delimiter. This means values (but not keys) can contain the delimiters. See also the space_around_delimiters argument to ConfigParser.write().
comment_prefixes, default value: ('#', ';')
inline_comment_prefixes, default value: None Comment prefixes are strings that indicate the start of a valid comment within a config file. comment_prefixes are used only on otherwise empty lines (optionally indented) whereas inline_comment_prefixes can be used after every valid value (e.g. section names, options and empty lines as well). By default inline comments are disabled and '#' and ';' are used as prefixes for whole line comments. Changed in version 3.2: In previous versions of configparser behaviour matched comment_prefixes=('#',';') and inline_comment_prefixes=(';',). Please note that config parsers don’t support escaping of comment prefixes so using inline_comment_prefixes may prevent users from specifying option values with characters used as comment prefixes. When in doubt, avoid setting inline_comment_prefixes. In any circumstances, the only way of storing comment prefix characters at the beginning of a line in multiline values is to interpolate the prefix, for example: >>> from configparser import ConfigParser, ExtendedInterpolation
>>> parser = ConfigParser(interpolation=ExtendedInterpolation())
>>> # the default BasicInterpolation could be used as well
>>> parser.read_string("""
... [DEFAULT]
... hash = #
...
... [hashes]
... shebang =
... ${hash}!/usr/bin/env python
... ${hash} -*- coding: utf-8 -*-
...
... extensions =
... enabled_extension
... another_extension
... #disabled_by_comment
... yet_another_extension
...
... interpolation not necessary = if # is not at line start
... even in multiline values = line #1
... line #2
... line #3
... """)
>>> print(parser['hashes']['shebang'])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
>>> print(parser['hashes']['extensions'])
enabled_extension
another_extension
yet_another_extension
>>> print(parser['hashes']['interpolation not necessary'])
if # is not at line start
>>> print(parser['hashes']['even in multiline values'])
line #1
line #2
line #3
strict, default value: True When set to True, the parser will not allow for any section or option duplicates while reading from a single source (using read_file(), read_string() or read_dict()). It is recommended to use strict parsers in new applications. Changed in version 3.2: In previous versions of configparser behaviour matched strict=False.
empty_lines_in_values, default value: True In config parsers, values can span multiple lines as long as they are indented more than the key that holds them. By default parsers also let empty lines to be parts of values. At the same time, keys can be arbitrarily indented themselves to improve readability. In consequence, when configuration files get big and complex, it is easy for the user to lose track of the file structure. Take for instance: [Section]
key = multiline
value with a gotcha
this = is still a part of the multiline value of 'key'
This can be especially problematic for the user to see if she’s using a proportional font to edit the file. That is why when your application does not need values with empty lines, you should consider disallowing them. This will make empty lines split keys every time. In the example above, it would produce two keys, key and this.
default_section, default value: configparser.DEFAULTSECT (that is: "DEFAULT") The convention of allowing a special section of default values for other sections or interpolation purposes is a powerful concept of this library, letting users create complex declarative configurations. This section is normally called "DEFAULT" but this can be customized to point to any other valid section name. Some typical values include: "general" or "common". The name provided is used for recognizing default sections when reading from any source and is used when writing configuration back to a file. Its current value can be retrieved using the parser_instance.default_section attribute and may be modified at runtime (i.e. to convert files from one format to another).
interpolation, default value: configparser.BasicInterpolation Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. RawConfigParser has a default value of None.
converters, default value: not set Config parsers provide option value getters that perform type conversion. By default getint(), getfloat(), and getboolean() are implemented. Should other getters be desirable, users may define them in a subclass or pass a dictionary where each key is a name of the converter and each value is a callable implementing said conversion. For instance, passing {'decimal': decimal.Decimal} would add getdecimal() on both the parser object and all section proxies. In other words, it will be possible to write both parser_instance.getdecimal('section', 'key', fallback=0) and parser_instance['section'].getdecimal('key', 0). If the converter needs to access the state of the parser, it can be implemented as a method on a config parser subclass. If the name of this method starts with get, it will be available on all section proxies, in the dict-compatible form (see the getdecimal() example above). More advanced customization may be achieved by overriding default values of these parser attributes. The defaults are defined on the classes, so they may be overridden by subclasses or by attribute assignment.
ConfigParser.BOOLEAN_STATES
By default when using getboolean(), config parsers consider the following values True: '1', 'yes', 'true', 'on' and the following values False: '0', 'no', 'false', 'off'. You can override this by specifying a custom dictionary of strings and their Boolean outcomes. For example: >>> custom = configparser.ConfigParser()
>>> custom['section1'] = {'funky': 'nope'}
>>> custom['section1'].getboolean('funky')
Traceback (most recent call last):
...
ValueError: Not a boolean: nope
>>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
>>> custom['section1'].getboolean('funky')
False
Other typical Boolean pairs include accept/reject or enabled/disabled.
ConfigParser.optionxform(option)
This method transforms option names on every read, get, or set operation. The default converts the name to lowercase. This also means that when a configuration file gets written, all keys will be lowercase. Override this method if that’s unsuitable. For example: >>> config = """
... [Section1]
... Key = Value
...
... [Section2]
... AnotherKey = Value
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> list(typical['Section1'].keys())
['key']
>>> list(typical['Section2'].keys())
['anotherkey']
>>> custom = configparser.RawConfigParser()
>>> custom.optionxform = lambda option: option
>>> custom.read_string(config)
>>> list(custom['Section1'].keys())
['Key']
>>> list(custom['Section2'].keys())
['AnotherKey']
Note The optionxform function transforms option names to a canonical form. This should be an idempotent function: if the name is already in canonical form, it should be returned unchanged.
ConfigParser.SECTCRE
A compiled regular expression used to parse section headers. The default matches [section] to the name "section". Whitespace is considered part of the section name, thus [ larch ] will be read as a section of name " larch ". Override this attribute if that’s unsuitable. For example: >>> import re
>>> config = """
... [Section 1]
... option = value
...
... [ Section 2 ]
... another = val
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', ' Section 2 ']
>>> custom = configparser.ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']
Note While ConfigParser objects also use an OPTCRE attribute for recognizing option lines, it’s not recommended to override it because that would interfere with constructor options allow_no_value and delimiters.
Legacy API Examples Mainly because of backwards compatibility concerns, configparser provides also a legacy API with explicit get/set methods. While there are valid use cases for the methods outlined below, mapping protocol access is preferred for new projects. The legacy API is at times more advanced, low-level and downright counterintuitive. An example of writing to a configuration file: import configparser
config = configparser.RawConfigParser()
# Please note that using RawConfigParser's set functions, you can assign
# non-string values to keys internally, but will receive an error when
# attempting to write to a file or when you get it in non-raw mode. Setting
# values using the mapping protocol or ConfigParser's set() does not allow
# such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'w') as configfile:
config.write(configfile)
An example of reading the configuration file again: import configparser
config = configparser.RawConfigParser()
config.read('example.cfg')
# getfloat() raises an exception if the value is not a float
# getint() and getboolean() also do this for their respective types
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print(a_float + an_int)
# Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
# This is because we are using a RawConfigParser().
if config.getboolean('Section1', 'a_bool'):
print(config.get('Section1', 'foo'))
To get interpolation, use ConfigParser: import configparser
cfg = configparser.ConfigParser()
cfg.read('example.cfg')
# Set the optional *raw* argument of get() to True if you wish to disable
# interpolation in a single get operation.
print(cfg.get('Section1', 'foo', raw=False)) # -> "Python is fun!"
print(cfg.get('Section1', 'foo', raw=True)) # -> "%(bar)s is %(baz)s!"
# The optional *vars* argument is a dict with members that will take
# precedence in interpolation.
print(cfg.get('Section1', 'foo', vars={'bar': 'Documentation',
'baz': 'evil'}))
# The optional *fallback* argument can be used to provide a fallback value
print(cfg.get('Section1', 'foo'))
# -> "Python is fun!"
print(cfg.get('Section1', 'foo', fallback='Monty is not.'))
# -> "Python is fun!"
print(cfg.get('Section1', 'monster', fallback='No such things as monsters.'))
# -> "No such things as monsters."
# A bare print(cfg.get('Section1', 'monster')) would raise NoOptionError
# but we can also use:
print(cfg.get('Section1', 'monster', fallback=None))
# -> None
Default values are available in both types of ConfigParsers. They are used in interpolation if an option used is not defined elsewhere. import configparser
# New instance with 'bar' and 'baz' defaulting to 'Life' and 'hard' each
config = configparser.ConfigParser({'bar': 'Life', 'baz': 'hard'})
config.read('example.cfg')
print(config.get('Section1', 'foo')) # -> "Python is fun!"
config.remove_option('Section1', 'bar')
config.remove_option('Section1', 'baz')
print(config.get('Section1', 'foo')) # -> "Life is hard!"
ConfigParser Objects
class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
The main configuration parser. When defaults is given, it is initialized into the dictionary of intrinsic defaults. When dict_type is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values. When delimiters is given, it is used as the set of substrings that divide keys from values. When comment_prefixes is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When inline_comment_prefixes is given, it will be used as the set of substrings that prefix comments in non-empty lines. When strict is True (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising DuplicateSectionError or DuplicateOptionError. When empty_lines_in_values is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When allow_no_value is True (default: False), options without values are accepted; the value held for these is None and they are serialized without the trailing delimiter. When default_section is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named "DEFAULT"). This value can be retrieved and changed on runtime using the default_section instance attribute. Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values foo %(bar)s and foo
%(BAR)s are equivalent. When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding get*() method on the parser object and section proxies. Changed in version 3.1: The default dict_type is collections.OrderedDict. Changed in version 3.2: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section and interpolation were added. Changed in version 3.5: The converters argument was added. Changed in version 3.7: The defaults argument is read with read_dict(), providing consistent behavior across the parser: non-string keys and values are implicitly converted to strings. Changed in version 3.8: The default dict_type is dict, since it now preserves insertion order.
defaults()
Return a dictionary containing the instance-wide defaults.
sections()
Return a list of the sections available; the default section is not included in the list.
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised. Changed in version 3.2: Non-string section names raise TypeError.
has_section(section)
Indicates whether the named section is present in the configuration. The default section is not acknowledged.
options(section)
Return a list of options available in the specified section.
has_option(section, option)
If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed.
read(filenames, encoding=None)
Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed. If filenames is a string, a bytes object or a path-like object, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read. If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files: import configparser, os
config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
encoding='cp1250')
New in version 3.2: The encoding parameter. Previously, all files were read using the default encoding for open(). New in version 3.6.1: The filenames parameter accepts a path-like object. New in version 3.7: The filenames parameter accepts a bytes object.
read_file(f, source=None)
Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode). Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'. New in version 3.2: Replaces readfp().
read_string(string, source='<string>')
Parse configuration data from a string. Optional argument source specifies a context-specific name of the string passed. If not given, '<string>' is used. This should commonly be a filesystem path or a URL. New in version 3.2.
read_dict(dictionary, source='<dict>')
Load configuration from any object that provides a dict-like items() method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. Optional argument source specifies a context-specific name of the dictionary passed. If not given, <dict> is used. This method can be used to copy state between parsers. New in version 3.2.
get(section, option, *, raw=False, vars=None[, fallback])
Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value. All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option. Changed in version 3.2: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol).
getint(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to an integer. See get() for explanation of raw, vars and fallback.
getfloat(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a floating point number. See get() for explanation of raw, vars and fallback.
getboolean(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback.
items(raw=False, vars=None)
items(section, raw=False, vars=None)
When section is not given, return a list of section_name, section_proxy pairs, including DEFAULTSECT. Otherwise, return a list of name, value pairs for the options in the given section. Optional arguments have the same meaning as for the get() method. Changed in version 3.8: Items present in vars no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation.
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. option and value must be strings; if not, TypeError is raised.
write(fileobject, space_around_delimiters=True)
Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces.
remove_option(section, option)
Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False.
remove_section(section)
Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.
optionxform(option)
Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive: cfgparser = ConfigParser()
cfgparser.optionxform = str
Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called.
readfp(fp, filename=None)
Deprecated since version 3.2: Use read_file() instead. Changed in version 3.2: readfp() now iterates on fp instead of calling fp.readline(). For existing code calling readfp() with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object: def readline_generator(fp):
line = fp.readline()
while line:
yield line
line = fp.readline()
Instead of parser.readfp(fp) use parser.read_file(readline_generator(fp)).
configparser.MAX_INTERPOLATION_DEPTH
The maximum depth for recursive interpolation for get() when the raw parameter is false. This is relevant only when the default interpolation is used.
RawConfigParser Objects
class configparser.RawConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])
Legacy variant of the ConfigParser. It has interpolation disabled by default and allows for non-string section names, option names, and values via its unsafe add_section and set methods, as well as the legacy defaults= keyword argument handling. Changed in version 3.8: The default dict_type is dict, since it now preserves insertion order. Note Consider using ConfigParser instead which checks types of the values to be stored internally. If you don’t want interpolation, you can use ConfigParser(interpolation=None).
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. Type of section is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors.
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. Use the mapping protocol API which does not allow such assignments to take place.
Exceptions
exception configparser.Error
Base class for all other configparser exceptions.
exception configparser.NoSectionError
Exception raised when a specified section is not found.
exception configparser.DuplicateSectionError
Exception raised if add_section() is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary. New in version 3.2: Optional source and lineno attributes and arguments to __init__() were added.
exception configparser.DuplicateOptionError
Exception raised by strict parsers if a single option appears twice during reading from a single file, string or dictionary. This catches misspellings and case sensitivity-related errors, e.g. a dictionary may have two keys representing the same case-insensitive configuration key.
exception configparser.NoOptionError
Exception raised when a specified option is not found in the specified section.
exception configparser.InterpolationError
Base class for exceptions raised when problems occur performing string interpolation.
exception configparser.InterpolationDepthError
Exception raised when string interpolation cannot be completed because the number of iterations exceeds MAX_INTERPOLATION_DEPTH. Subclass of InterpolationError.
exception configparser.InterpolationMissingOptionError
Exception raised when an option referenced from a value does not exist. Subclass of InterpolationError.
exception configparser.InterpolationSyntaxError
Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of InterpolationError.
exception configparser.MissingSectionHeaderError
Exception raised when attempting to parse a file which has no section headers.
exception configparser.ParsingError
Exception raised when errors occur attempting to parse a file. Changed in version 3.2: The filename attribute and __init__() argument were renamed to source for consistency.
Footnotes
1(1,2,3,4,5,6,7,8,9,10)
Config parsers allow for heavy customization. If you are interested in changing the behaviour outlined by the footnote reference, consult the Customizing Parser Behaviour section. | python.library.configparser |
class configparser.BasicInterpolation
The default implementation used by ConfigParser. It enables values to contain format strings which refer to other values in the same section, or values in the special default section 1. Additional default values can be provided on initialization. For example: [Paths]
home_dir: /Users
my_dir: %(home_dir)s/lumberjack
my_pictures: %(my_dir)s/Pictures
[Escape]
gain: 80%% # use a %% to escape the % sign (% is the only character that needs to be escaped)
In the example above, ConfigParser with interpolation set to BasicInterpolation() would resolve %(home_dir)s to the value of home_dir (/Users in this case). %(my_dir)s in effect would resolve to /Users/lumberjack. All interpolations are done on demand so keys used in the chain of references do not have to be specified in any specific order in the configuration file. With interpolation set to None, the parser would simply return %(my_dir)s/Pictures as the value of my_pictures and %(home_dir)s/lumberjack as the value of my_dir. | python.library.configparser#configparser.BasicInterpolation |
class configparser.ConfigParser(defaults=None, dict_type=dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT, interpolation=BasicInterpolation(), converters={})
The main configuration parser. When defaults is given, it is initialized into the dictionary of intrinsic defaults. When dict_type is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values. When delimiters is given, it is used as the set of substrings that divide keys from values. When comment_prefixes is given, it will be used as the set of substrings that prefix comments in otherwise empty lines. Comments can be indented. When inline_comment_prefixes is given, it will be used as the set of substrings that prefix comments in non-empty lines. When strict is True (the default), the parser won’t allow for any section or option duplicates while reading from a single source (file, string or dictionary), raising DuplicateSectionError or DuplicateOptionError. When empty_lines_in_values is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When allow_no_value is True (default: False), options without values are accepted; the value held for these is None and they are serialized without the trailing delimiter. When default_section is given, it specifies the name for the special section holding default values for other sections and interpolation purposes (normally named "DEFAULT"). This value can be retrieved and changed on runtime using the default_section instance attribute. Interpolation behaviour may be customized by providing a custom handler through the interpolation argument. None can be used to turn off interpolation completely, ExtendedInterpolation() provides a more advanced variant inspired by zc.buildout. More on the subject in the dedicated documentation section. All option names used in interpolation will be passed through the optionxform() method just like any other option name reference. For example, using the default implementation of optionxform() (which converts option names to lower case), the values foo %(bar)s and foo
%(BAR)s are equivalent. When converters is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its own corresponding get*() method on the parser object and section proxies. Changed in version 3.1: The default dict_type is collections.OrderedDict. Changed in version 3.2: allow_no_value, delimiters, comment_prefixes, strict, empty_lines_in_values, default_section and interpolation were added. Changed in version 3.5: The converters argument was added. Changed in version 3.7: The defaults argument is read with read_dict(), providing consistent behavior across the parser: non-string keys and values are implicitly converted to strings. Changed in version 3.8: The default dict_type is dict, since it now preserves insertion order.
defaults()
Return a dictionary containing the instance-wide defaults.
sections()
Return a list of the sections available; the default section is not included in the list.
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised. Changed in version 3.2: Non-string section names raise TypeError.
has_section(section)
Indicates whether the named section is present in the configuration. The default section is not acknowledged.
options(section)
Return a list of options available in the specified section.
has_option(section, option)
If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed.
read(filenames, encoding=None)
Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed. If filenames is a string, a bytes object or a path-like object, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read. If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files: import configparser, os
config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
encoding='cp1250')
New in version 3.2: The encoding parameter. Previously, all files were read using the default encoding for open(). New in version 3.6.1: The filenames parameter accepts a path-like object. New in version 3.7: The filenames parameter accepts a bytes object.
read_file(f, source=None)
Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode). Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'. New in version 3.2: Replaces readfp().
read_string(string, source='<string>')
Parse configuration data from a string. Optional argument source specifies a context-specific name of the string passed. If not given, '<string>' is used. This should commonly be a filesystem path or a URL. New in version 3.2.
read_dict(dictionary, source='<dict>')
Load configuration from any object that provides a dict-like items() method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. Optional argument source specifies a context-specific name of the dictionary passed. If not given, <dict> is used. This method can be used to copy state between parsers. New in version 3.2.
get(section, option, *, raw=False, vars=None[, fallback])
Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value. All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option. Changed in version 3.2: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol).
getint(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to an integer. See get() for explanation of raw, vars and fallback.
getfloat(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a floating point number. See get() for explanation of raw, vars and fallback.
getboolean(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback.
items(raw=False, vars=None)
items(section, raw=False, vars=None)
When section is not given, return a list of section_name, section_proxy pairs, including DEFAULTSECT. Otherwise, return a list of name, value pairs for the options in the given section. Optional arguments have the same meaning as for the get() method. Changed in version 3.8: Items present in vars no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation.
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. option and value must be strings; if not, TypeError is raised.
write(fileobject, space_around_delimiters=True)
Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces.
remove_option(section, option)
Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False.
remove_section(section)
Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False.
optionxform(option)
Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive: cfgparser = ConfigParser()
cfgparser.optionxform = str
Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called.
readfp(fp, filename=None)
Deprecated since version 3.2: Use read_file() instead. Changed in version 3.2: readfp() now iterates on fp instead of calling fp.readline(). For existing code calling readfp() with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object: def readline_generator(fp):
line = fp.readline()
while line:
yield line
line = fp.readline()
Instead of parser.readfp(fp) use parser.read_file(readline_generator(fp)). | python.library.configparser#configparser.ConfigParser |
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. The name of the section must be a string; if not, TypeError is raised. Changed in version 3.2: Non-string section names raise TypeError. | python.library.configparser#configparser.ConfigParser.add_section |
ConfigParser.BOOLEAN_STATES
By default when using getboolean(), config parsers consider the following values True: '1', 'yes', 'true', 'on' and the following values False: '0', 'no', 'false', 'off'. You can override this by specifying a custom dictionary of strings and their Boolean outcomes. For example: >>> custom = configparser.ConfigParser()
>>> custom['section1'] = {'funky': 'nope'}
>>> custom['section1'].getboolean('funky')
Traceback (most recent call last):
...
ValueError: Not a boolean: nope
>>> custom.BOOLEAN_STATES = {'sure': True, 'nope': False}
>>> custom['section1'].getboolean('funky')
False
Other typical Boolean pairs include accept/reject or enabled/disabled. | python.library.configparser#configparser.ConfigParser.BOOLEAN_STATES |
defaults()
Return a dictionary containing the instance-wide defaults. | python.library.configparser#configparser.ConfigParser.defaults |
get(section, option, *, raw=False, vars=None[, fallback])
Get an option value for the named section. If vars is provided, it must be a dictionary. The option is looked up in vars (if provided), section, and in DEFAULTSECT in that order. If the key is not found and fallback is provided, it is used as a fallback value. None can be provided as a fallback value. All the '%' interpolations are expanded in the return values, unless the raw argument is true. Values for interpolation keys are looked up in the same manner as the option. Changed in version 3.2: Arguments raw, vars and fallback are keyword only to protect users from trying to use the third argument as the fallback fallback (especially when using the mapping protocol). | python.library.configparser#configparser.ConfigParser.get |
getboolean(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a Boolean value. Note that the accepted values for the option are '1', 'yes', 'true', and 'on', which cause this method to return True, and '0', 'no', 'false', and 'off', which cause it to return False. These string values are checked in a case-insensitive manner. Any other value will cause it to raise ValueError. See get() for explanation of raw, vars and fallback. | python.library.configparser#configparser.ConfigParser.getboolean |
getfloat(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to a floating point number. See get() for explanation of raw, vars and fallback. | python.library.configparser#configparser.ConfigParser.getfloat |
getint(section, option, *, raw=False, vars=None[, fallback])
A convenience method which coerces the option in the specified section to an integer. See get() for explanation of raw, vars and fallback. | python.library.configparser#configparser.ConfigParser.getint |
has_option(section, option)
If the given section exists, and contains the given option, return True; otherwise return False. If the specified section is None or an empty string, DEFAULT is assumed. | python.library.configparser#configparser.ConfigParser.has_option |
has_section(section)
Indicates whether the named section is present in the configuration. The default section is not acknowledged. | python.library.configparser#configparser.ConfigParser.has_section |
items(raw=False, vars=None)
items(section, raw=False, vars=None)
When section is not given, return a list of section_name, section_proxy pairs, including DEFAULTSECT. Otherwise, return a list of name, value pairs for the options in the given section. Optional arguments have the same meaning as for the get() method. Changed in version 3.8: Items present in vars no longer appear in the result. The previous behaviour mixed actual parser options with variables provided for interpolation. | python.library.configparser#configparser.ConfigParser.items |
options(section)
Return a list of options available in the specified section. | python.library.configparser#configparser.ConfigParser.options |
optionxform(option)
Transforms the option name option as found in an input file or as passed in by client code to the form that should be used in the internal structures. The default implementation returns a lower-case version of option; subclasses may override this or client code can set an attribute of this name on instances to affect this behavior. You don’t need to subclass the parser to use this method, you can also set it on an instance, to a function that takes a string argument and returns a string. Setting it to str, for example, would make option names case sensitive: cfgparser = ConfigParser()
cfgparser.optionxform = str
Note that when reading configuration files, whitespace around the option names is stripped before optionxform() is called. | python.library.configparser#configparser.ConfigParser.optionxform |
read(filenames, encoding=None)
Attempt to read and parse an iterable of filenames, returning a list of filenames which were successfully parsed. If filenames is a string, a bytes object or a path-like object, it is treated as a single filename. If a file named in filenames cannot be opened, that file will be ignored. This is designed so that you can specify an iterable of potential configuration file locations (for example, the current directory, the user’s home directory, and some system-wide directory), and all existing configuration files in the iterable will be read. If none of the named files exist, the ConfigParser instance will contain an empty dataset. An application which requires initial values to be loaded from a file should load the required file or files using read_file() before calling read() for any optional files: import configparser, os
config = configparser.ConfigParser()
config.read_file(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')],
encoding='cp1250')
New in version 3.2: The encoding parameter. Previously, all files were read using the default encoding for open(). New in version 3.6.1: The filenames parameter accepts a path-like object. New in version 3.7: The filenames parameter accepts a bytes object. | python.library.configparser#configparser.ConfigParser.read |
readfp(fp, filename=None)
Deprecated since version 3.2: Use read_file() instead. Changed in version 3.2: readfp() now iterates on fp instead of calling fp.readline(). For existing code calling readfp() with arguments which don’t support iteration, the following generator may be used as a wrapper around the file-like object: def readline_generator(fp):
line = fp.readline()
while line:
yield line
line = fp.readline()
Instead of parser.readfp(fp) use parser.read_file(readline_generator(fp)). | python.library.configparser#configparser.ConfigParser.readfp |
read_dict(dictionary, source='<dict>')
Load configuration from any object that provides a dict-like items() method. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. Optional argument source specifies a context-specific name of the dictionary passed. If not given, <dict> is used. This method can be used to copy state between parsers. New in version 3.2. | python.library.configparser#configparser.ConfigParser.read_dict |
read_file(f, source=None)
Read and parse configuration data from f which must be an iterable yielding Unicode strings (for example files opened in text mode). Optional argument source specifies the name of the file being read. If not given and f has a name attribute, that is used for source; the default is '<???>'. New in version 3.2: Replaces readfp(). | python.library.configparser#configparser.ConfigParser.read_file |
read_string(string, source='<string>')
Parse configuration data from a string. Optional argument source specifies a context-specific name of the string passed. If not given, '<string>' is used. This should commonly be a filesystem path or a URL. New in version 3.2. | python.library.configparser#configparser.ConfigParser.read_string |
remove_option(section, option)
Remove the specified option from the specified section. If the section does not exist, raise NoSectionError. If the option existed to be removed, return True; otherwise return False. | python.library.configparser#configparser.ConfigParser.remove_option |
remove_section(section)
Remove the specified section from the configuration. If the section in fact existed, return True. Otherwise return False. | python.library.configparser#configparser.ConfigParser.remove_section |
ConfigParser.SECTCRE
A compiled regular expression used to parse section headers. The default matches [section] to the name "section". Whitespace is considered part of the section name, thus [ larch ] will be read as a section of name " larch ". Override this attribute if that’s unsuitable. For example: >>> import re
>>> config = """
... [Section 1]
... option = value
...
... [ Section 2 ]
... another = val
... """
>>> typical = configparser.ConfigParser()
>>> typical.read_string(config)
>>> typical.sections()
['Section 1', ' Section 2 ']
>>> custom = configparser.ConfigParser()
>>> custom.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]")
>>> custom.read_string(config)
>>> custom.sections()
['Section 1', 'Section 2']
Note While ConfigParser objects also use an OPTCRE attribute for recognizing option lines, it’s not recommended to override it because that would interfere with constructor options allow_no_value and delimiters. | python.library.configparser#configparser.ConfigParser.SECTCRE |
sections()
Return a list of the sections available; the default section is not included in the list. | python.library.configparser#configparser.ConfigParser.sections |
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. option and value must be strings; if not, TypeError is raised. | python.library.configparser#configparser.ConfigParser.set |
write(fileobject, space_around_delimiters=True)
Write a representation of the configuration to the specified file object, which must be opened in text mode (accepting strings). This representation can be parsed by a future read() call. If space_around_delimiters is true, delimiters between keys and values are surrounded by spaces. | python.library.configparser#configparser.ConfigParser.write |
exception configparser.DuplicateOptionError
Exception raised by strict parsers if a single option appears twice during reading from a single file, string or dictionary. This catches misspellings and case sensitivity-related errors, e.g. a dictionary may have two keys representing the same case-insensitive configuration key. | python.library.configparser#configparser.DuplicateOptionError |
exception configparser.DuplicateSectionError
Exception raised if add_section() is called with the name of a section that is already present or in strict parsers when a section if found more than once in a single input file, string or dictionary. New in version 3.2: Optional source and lineno attributes and arguments to __init__() were added. | python.library.configparser#configparser.DuplicateSectionError |
exception configparser.Error
Base class for all other configparser exceptions. | python.library.configparser#configparser.Error |
class configparser.ExtendedInterpolation
An alternative handler for interpolation which implements a more advanced syntax, used for instance in zc.buildout. Extended interpolation is using ${section:option} to denote a value from a foreign section. Interpolation can span multiple levels. For convenience, if the section: part is omitted, interpolation defaults to the current section (and possibly the default values from the special section). For example, the configuration specified above with basic interpolation, would look like this with extended interpolation: [Paths]
home_dir: /Users
my_dir: ${home_dir}/lumberjack
my_pictures: ${my_dir}/Pictures
[Escape]
cost: $$80 # use a $$ to escape the $ sign ($ is the only character that needs to be escaped)
Values from other sections can be fetched as well: [Common]
home_dir: /Users
library_dir: /Library
system_dir: /System
macports_dir: /opt/local
[Frameworks]
Python: 3.2
path: ${Common:system_dir}/Library/Frameworks/
[Arthur]
nickname: Two Sheds
last_name: Jackson
my_dir: ${Common:home_dir}/twosheds
my_pictures: ${my_dir}/Pictures
python_dir: ${Frameworks:path}/Python/Versions/${Frameworks:Python} | python.library.configparser#configparser.ExtendedInterpolation |
exception configparser.InterpolationDepthError
Exception raised when string interpolation cannot be completed because the number of iterations exceeds MAX_INTERPOLATION_DEPTH. Subclass of InterpolationError. | python.library.configparser#configparser.InterpolationDepthError |
exception configparser.InterpolationError
Base class for exceptions raised when problems occur performing string interpolation. | python.library.configparser#configparser.InterpolationError |
exception configparser.InterpolationMissingOptionError
Exception raised when an option referenced from a value does not exist. Subclass of InterpolationError. | python.library.configparser#configparser.InterpolationMissingOptionError |
exception configparser.InterpolationSyntaxError
Exception raised when the source text into which substitutions are made does not conform to the required syntax. Subclass of InterpolationError. | python.library.configparser#configparser.InterpolationSyntaxError |
configparser.MAX_INTERPOLATION_DEPTH
The maximum depth for recursive interpolation for get() when the raw parameter is false. This is relevant only when the default interpolation is used. | python.library.configparser#configparser.MAX_INTERPOLATION_DEPTH |
exception configparser.MissingSectionHeaderError
Exception raised when attempting to parse a file which has no section headers. | python.library.configparser#configparser.MissingSectionHeaderError |
exception configparser.NoOptionError
Exception raised when a specified option is not found in the specified section. | python.library.configparser#configparser.NoOptionError |
exception configparser.NoSectionError
Exception raised when a specified section is not found. | python.library.configparser#configparser.NoSectionError |
exception configparser.ParsingError
Exception raised when errors occur attempting to parse a file. Changed in version 3.2: The filename attribute and __init__() argument were renamed to source for consistency. | python.library.configparser#configparser.ParsingError |
class configparser.RawConfigParser(defaults=None, dict_type=dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=configparser.DEFAULTSECT[, interpolation])
Legacy variant of the ConfigParser. It has interpolation disabled by default and allows for non-string section names, option names, and values via its unsafe add_section and set methods, as well as the legacy defaults= keyword argument handling. Changed in version 3.8: The default dict_type is dict, since it now preserves insertion order. Note Consider using ConfigParser instead which checks types of the values to be stored internally. If you don’t want interpolation, you can use ConfigParser(interpolation=None).
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. Type of section is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors.
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. Use the mapping protocol API which does not allow such assignments to take place. | python.library.configparser#configparser.RawConfigParser |
add_section(section)
Add a section named section to the instance. If a section by the given name already exists, DuplicateSectionError is raised. If the default section name is passed, ValueError is raised. Type of section is not checked which lets users create non-string named sections. This behaviour is unsupported and may cause internal errors. | python.library.configparser#configparser.RawConfigParser.add_section |
set(section, option, value)
If the given section exists, set the given option to the specified value; otherwise raise NoSectionError. While it is possible to use RawConfigParser (or ConfigParser with raw parameters set to true) for internal storage of non-string values, full functionality (including interpolation and output to files) can only be achieved using string values. This method lets users assign non-string values to keys internally. This behaviour is unsupported and will cause errors when attempting to write to a file or get it in non-raw mode. Use the mapping protocol API which does not allow such assignments to take place. | python.library.configparser#configparser.RawConfigParser.set |
exception ConnectionAbortedError
A subclass of ConnectionError, raised when a connection attempt is aborted by the peer. Corresponds to errno ECONNABORTED. | python.library.exceptions#ConnectionAbortedError |
exception ConnectionError
A base class for connection-related issues. Subclasses are BrokenPipeError, ConnectionAbortedError, ConnectionRefusedError and ConnectionResetError. | python.library.exceptions#ConnectionError |
exception ConnectionRefusedError
A subclass of ConnectionError, raised when a connection attempt is refused by the peer. Corresponds to errno ECONNREFUSED. | python.library.exceptions#ConnectionRefusedError |
exception ConnectionResetError
A subclass of ConnectionError, raised when a connection is reset by the peer. Corresponds to errno ECONNRESET. | python.library.exceptions#ConnectionResetError |
Built-in Constants A small number of constants live in the built-in namespace. They are:
False
The false value of the bool type. Assignments to False are illegal and raise a SyntaxError.
True
The true value of the bool type. Assignments to True are illegal and raise a SyntaxError.
None
The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.
NotImplemented
Special value which should be returned by the binary special methods (e.g. __eq__(), __lt__(), __add__(), __rsub__(), etc.) to indicate that the operation is not implemented with respect to the other type; may be returned by the in-place binary special methods (e.g. __imul__(), __iand__(), etc.) for the same purpose. It should not be evaluated in a boolean context. Note When a binary (or in-place) method returns NotImplemented the interpreter will try the reflected operation on the other type (or some other fallback, depending on the operator). If all attempts return NotImplemented, the interpreter will raise an appropriate exception. Incorrectly returning NotImplemented will result in a misleading error message or the NotImplemented value being returned to Python code. See Implementing the arithmetic operations for examples. Note NotImplementedError and NotImplemented are not interchangeable, even though they have similar names and purposes. See NotImplementedError for details on when to use it. Changed in version 3.9: Evaluating NotImplemented in a boolean context is deprecated. While it currently evaluates as true, it will emit a DeprecationWarning. It will raise a TypeError in a future version of Python.
Ellipsis
The same as the ellipsis literal “...”. Special value used mostly in conjunction with extended slicing syntax for user-defined container data types.
__debug__
This constant is true if Python was not started with an -O option. See also the assert statement.
Note The names None, False, True and __debug__ cannot be reassigned (assignments to them, even as an attribute name, raise SyntaxError), so they can be considered “true” constants. Constants added by the site module The site module (which is imported automatically during startup, except if the -S command-line option is given) adds several constants to the built-in namespace. They are useful for the interactive interpreter shell and should not be used in programs.
quit(code=None)
exit(code=None)
Objects that when printed, print a message like “Use quit() or Ctrl-D (i.e. EOF) to exit”, and when called, raise SystemExit with the specified exit code.
copyright
credits
Objects that when printed or called, print the text of copyright or credits, respectively.
license
Object that when printed, prints the message “Type license() to see the full license text”, and when called, displays the full license text in a pager-like fashion (one screen at a time). | python.library.constants |
container.__iter__()
Return an iterator object. The object is required to support the iterator protocol described below. If a container supports different types of iteration, additional methods can be provided to specifically request iterators for those iteration types. (An example of an object supporting multiple forms of iteration would be a tree structure which supports both breadth-first and depth-first traversal.) This method corresponds to the tp_iter slot of the type structure for Python objects in the Python/C API. | python.library.stdtypes#container.__iter__ |
contextlib — Utilities for with-statement contexts Source code: Lib/contextlib.py This module provides utilities for common tasks involving the with statement. For more information see also Context Manager Types and With Statement Context Managers. Utilities Functions and classes provided:
class contextlib.AbstractContextManager
An abstract base class for classes that implement object.__enter__() and object.__exit__(). A default implementation for object.__enter__() is provided which returns self while object.__exit__() is an abstract method which by default returns None. See also the definition of Context Manager Types. New in version 3.6.
class contextlib.AbstractAsyncContextManager
An abstract base class for classes that implement object.__aenter__() and object.__aexit__(). A default implementation for object.__aenter__() is provided which returns self while object.__aexit__() is an abstract method which by default returns None. See also the definition of Asynchronous Context Managers. New in version 3.7.
@contextlib.contextmanager
This function is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods. While many objects natively support use in with statements, sometimes a resource needs to be managed that isn’t a context manager in its own right, and doesn’t implement a close() method for use with contextlib.closing An abstract example would be the following to ensure correct resource management: from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
# Code to acquire resource, e.g.:
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
# Code to release resource, e.g.:
release_resource(resource)
>>> with managed_resource(timeout=3600) as resource:
... # Resource is released at the end of this block,
... # even if code in the block raises an exception
The function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any. At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a try…except…finally statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the with statement that the exception has been handled, and execution will resume with the statement immediately following the with statement. contextmanager() uses ContextDecorator so the context managers it creates can be used as decorators as well as in with statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise “one-shot” context managers created by contextmanager() to meet the requirement that context managers support multiple invocations in order to be used as decorators). Changed in version 3.2: Use of ContextDecorator.
@contextlib.asynccontextmanager
Similar to contextmanager(), but creates an asynchronous context manager. This function is a decorator that can be used to define a factory function for async with statement asynchronous context managers, without needing to create a class or separate __aenter__() and __aexit__() methods. It must be applied to an asynchronous generator function. A simple example: from contextlib import asynccontextmanager
@asynccontextmanager
async def get_connection():
conn = await acquire_db_connection()
try:
yield conn
finally:
await release_db_connection(conn)
async def get_all_users():
async with get_connection() as conn:
return conn.query('SELECT ...')
New in version 3.7.
contextlib.closing(thing)
Return a context manager that closes thing upon completion of the block. This is basically equivalent to: from contextlib import contextmanager
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
And lets you write code like this: from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('http://www.python.org')) as page:
for line in page:
print(line)
without needing to explicitly close page. Even if an error occurs, page.close() will be called when the with block is exited.
contextlib.nullcontext(enter_result=None)
Return a context manager that returns enter_result from __enter__, but otherwise does nothing. It is intended to be used as a stand-in for an optional context manager, for example: def myfunction(arg, ignore_exceptions=False):
if ignore_exceptions:
# Use suppress to ignore all exceptions.
cm = contextlib.suppress(Exception)
else:
# Do not ignore any exceptions, cm has no effect.
cm = contextlib.nullcontext()
with cm:
# Do something
An example using enter_result: def process_file(file_or_path):
if isinstance(file_or_path, str):
# If string, open file
cm = open(file_or_path)
else:
# Caller is responsible for closing file
cm = nullcontext(file_or_path)
with cm as file:
# Perform processing on the file
New in version 3.7.
contextlib.suppress(*exceptions)
Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement. As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do. For example: from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
with suppress(FileNotFoundError):
os.remove('someotherfile.tmp')
This code is equivalent to: try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
try:
os.remove('someotherfile.tmp')
except FileNotFoundError:
pass
This context manager is reentrant. New in version 3.4.
contextlib.redirect_stdout(new_target)
Context manager for temporarily redirecting sys.stdout to another file or file-like object. This tool adds flexibility to existing functions or classes whose output is hardwired to stdout. For example, the output of help() normally is sent to sys.stdout. You can capture that output in a string by redirecting the output to an io.StringIO object: f = io.StringIO()
with redirect_stdout(f):
help(pow)
s = f.getvalue()
To send the output of help() to a file on disk, redirect the output to a regular file: with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
To send the output of help() to sys.stderr: with redirect_stdout(sys.stderr):
help(pow)
Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts. This context manager is reentrant. New in version 3.4.
contextlib.redirect_stderr(new_target)
Similar to redirect_stdout() but redirecting sys.stderr to another file or file-like object. This context manager is reentrant. New in version 3.5.
class contextlib.ContextDecorator
A base class that enables a context manager to also be used as a decorator. Context managers inheriting from ContextDecorator have to implement __enter__ and __exit__ as normal. __exit__ retains its optional exception handling even when used as a decorator. ContextDecorator is used by contextmanager(), so you get this functionality automatically. Example of ContextDecorator: from contextlib import ContextDecorator
class mycontext(ContextDecorator):
def __enter__(self):
print('Starting')
return self
def __exit__(self, *exc):
print('Finishing')
return False
>>> @mycontext()
... def function():
... print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing
>>> with mycontext():
... print('The bit in the middle')
...
Starting
The bit in the middle
Finishing
This change is just syntactic sugar for any construct of the following form: def f():
with cm():
# Do stuff
ContextDecorator lets you instead write: @cm()
def f():
# Do stuff
It makes it clear that the cm applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too). Existing context managers that already have a base class can be extended by using ContextDecorator as a mixin class: from contextlib import ContextDecorator
class mycontext(ContextBaseClass, ContextDecorator):
def __enter__(self):
return self
def __exit__(self, *exc):
return False
Note As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple with statements. If this is not the case, then the original construct with the explicit with statement inside the function should be used. New in version 3.2.
class contextlib.ExitStack
A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data. For example, a set of files may easily be handled in a single with statement as follows: with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected. This stack model is used so that context managers that acquire their resources in their __init__ method (such as file objects) can be handled correctly. Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state. This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways. New in version 3.3.
enter_context(cm)
Enters a new context manager and adds its __exit__() method to the callback stack. The return value is the result of the context manager’s own __enter__() method. These context managers may suppress exceptions just as they normally would if used directly as part of a with statement.
push(exit)
Adds a context manager’s __exit__() method to the callback stack. As __enter__ is not invoked, this method can be used to cover part of an __enter__() implementation with a context manager’s own __exit__() method. If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s __exit__() method and adds it directly to the callback stack. By returning true values, these callbacks can suppress exceptions the same way context manager __exit__() methods can. The passed in object is returned from the function, allowing this method to be used as a function decorator.
callback(callback, /, *args, **kwds)
Accepts an arbitrary callback function and arguments and adds it to the callback stack. Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). The passed in callback is returned from the function, allowing this method to be used as a function decorator.
pop_all()
Transfers the callback stack to a fresh ExitStack instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a with statement). For example, a group of files can be opened as an “all or nothing” operation as follows: with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Hold onto the close method, but don't call it yet.
close_files = stack.pop_all().close
# If opening any file fails, all previously opened files will be
# closed automatically. If all files are opened successfully,
# they will remain open even after the with statement ends.
# close_files() can then be invoked explicitly to close them all.
close()
Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred.
class contextlib.AsyncExitStack
An asynchronous context manager, similar to ExitStack, that supports combining both synchronous and asynchronous context managers, as well as having coroutines for cleanup logic. The close() method is not implemented, aclose() must be used instead.
enter_async_context(cm)
Similar to enter_context() but expects an asynchronous context manager.
push_async_exit(exit)
Similar to push() but expects either an asynchronous context manager or a coroutine function.
push_async_callback(callback, /, *args, **kwds)
Similar to callback() but expects a coroutine function.
aclose()
Similar to close() but properly handles awaitables.
Continuing the example for asynccontextmanager(): async with AsyncExitStack() as stack:
connections = [await stack.enter_async_context(get_connection())
for i in range(5)]
# All opened connections will automatically be released at the end of
# the async with statement, even if attempts to open a connection
# later in the list raise an exception.
New in version 3.7.
Examples and Recipes This section describes some examples and recipes for making effective use of the tools provided by contextlib. Supporting a variable number of context managers The primary use case for ExitStack is the one given in the class documentation: supporting a variable number of context managers and other cleanup operations in a single with statement. The variability may come from the number of context managers needed being driven by user input (such as opening a user specified collection of files), or from some of the context managers being optional: with ExitStack() as stack:
for resource in resources:
stack.enter_context(resource)
if need_special_resource():
special = acquire_special_resource()
stack.callback(release_special_resource, special)
# Perform operations that use the acquired resources
As shown, ExitStack also makes it quite easy to use with statements to manage arbitrary resources that don’t natively support the context management protocol. Catching exceptions from __enter__ methods It is occasionally desirable to catch exceptions from an __enter__ method implementation, without inadvertently catching exceptions from the with statement body or the context manager’s __exit__ method. By using ExitStack the steps in the context management protocol can be separated slightly in order to allow this: stack = ExitStack()
try:
x = stack.enter_context(cm)
except Exception:
# handle __enter__ exception
else:
with stack:
# Handle normal case
Actually needing to do this is likely to indicate that the underlying API should be providing a direct resource management interface for use with try/except/finally statements, but not all APIs are well designed in that regard. When a context manager is the only resource management API provided, then ExitStack can make it easier to handle various situations that can’t be handled directly in a with statement. Cleaning up in an __enter__ implementation As noted in the documentation of ExitStack.push(), this method can be useful in cleaning up an already allocated resource if later steps in the __enter__() implementation fail. Here’s an example of doing this for a context manager that accepts resource acquisition and release functions, along with an optional validation function, and maps them to the context management protocol: from contextlib import contextmanager, AbstractContextManager, ExitStack
class ResourceManager(AbstractContextManager):
def __init__(self, acquire_resource, release_resource, check_resource_ok=None):
self.acquire_resource = acquire_resource
self.release_resource = release_resource
if check_resource_ok is None:
def check_resource_ok(resource):
return True
self.check_resource_ok = check_resource_ok
@contextmanager
def _cleanup_on_error(self):
with ExitStack() as stack:
stack.push(self)
yield
# The validation check passed and didn't raise an exception
# Accordingly, we want to keep the resource, and pass it
# back to our caller
stack.pop_all()
def __enter__(self):
resource = self.acquire_resource()
with self._cleanup_on_error():
if not self.check_resource_ok(resource):
msg = "Failed validation for {!r}"
raise RuntimeError(msg.format(resource))
return resource
def __exit__(self, *exc_details):
# We don't need to duplicate any of our resource release logic
self.release_resource()
Replacing any use of try-finally and flag variables A pattern you will sometimes see is a try-finally statement with a flag variable to indicate whether or not the body of the finally clause should be executed. In its simplest form (that can’t already be handled just by using an except clause instead), it looks something like this: cleanup_needed = True
try:
result = perform_operation()
if result:
cleanup_needed = False
finally:
if cleanup_needed:
cleanup_resources()
As with any try statement based code, this can cause problems for development and review, because the setup code and the cleanup code can end up being separated by arbitrarily long sections of code. ExitStack makes it possible to instead register a callback for execution at the end of a with statement, and then later decide to skip executing that callback: from contextlib import ExitStack
with ExitStack() as stack:
stack.callback(cleanup_resources)
result = perform_operation()
if result:
stack.pop_all()
This allows the intended cleanup up behaviour to be made explicit up front, rather than requiring a separate flag variable. If a particular application uses this pattern a lot, it can be simplified even further by means of a small helper class: from contextlib import ExitStack
class Callback(ExitStack):
def __init__(self, callback, /, *args, **kwds):
super().__init__()
self.callback(callback, *args, **kwds)
def cancel(self):
self.pop_all()
with Callback(cleanup_resources) as cb:
result = perform_operation()
if result:
cb.cancel()
If the resource cleanup isn’t already neatly bundled into a standalone function, then it is still possible to use the decorator form of ExitStack.callback() to declare the resource cleanup in advance: from contextlib import ExitStack
with ExitStack() as stack:
@stack.callback
def cleanup_resources():
...
result = perform_operation()
if result:
stack.pop_all()
Due to the way the decorator protocol works, a callback function declared this way cannot take any parameters. Instead, any resources to be released must be accessed as closure variables. Using a context manager as a function decorator ContextDecorator makes it possible to use a context manager in both an ordinary with statement and also as a function decorator. For example, it is sometimes useful to wrap functions or groups of statements with a logger that can track the time of entry and time of exit. Rather than writing both a function decorator and a context manager for the task, inheriting from ContextDecorator provides both capabilities in a single definition: from contextlib import ContextDecorator
import logging
logging.basicConfig(level=logging.INFO)
class track_entry_and_exit(ContextDecorator):
def __init__(self, name):
self.name = name
def __enter__(self):
logging.info('Entering: %s', self.name)
def __exit__(self, exc_type, exc, exc_tb):
logging.info('Exiting: %s', self.name)
Instances of this class can be used as both a context manager: with track_entry_and_exit('widget loader'):
print('Some time consuming activity goes here')
load_widget()
And also as a function decorator: @track_entry_and_exit('widget loader')
def activity():
print('Some time consuming activity goes here')
load_widget()
Note that there is one additional limitation when using context managers as function decorators: there’s no way to access the return value of __enter__(). If that value is needed, then it is still necessary to use an explicit with statement. See also
PEP 343 - The “with” statement
The specification, background, and examples for the Python with statement. Single use, reusable and reentrant context managers Most context managers are written in a way that means they can only be used effectively in a with statement once. These single use context managers must be created afresh each time they’re used - attempting to use them a second time will trigger an exception or otherwise not work correctly. This common limitation means that it is generally advisable to create context managers directly in the header of the with statement where they are used (as shown in all of the usage examples above). Files are an example of effectively single use context managers, since the first with statement will close the file, preventing any further IO operations using that file object. Context managers created using contextmanager() are also single use context managers, and will complain about the underlying generator failing to yield if an attempt is made to use them a second time: >>> from contextlib import contextmanager
>>> @contextmanager
... def singleuse():
... print("Before")
... yield
... print("After")
...
>>> cm = singleuse()
>>> with cm:
... pass
...
Before
After
>>> with cm:
... pass
...
Traceback (most recent call last):
...
RuntimeError: generator didn't yield
Reentrant context managers More sophisticated context managers may be “reentrant”. These context managers can not only be used in multiple with statements, but may also be used inside a with statement that is already using the same context manager. threading.RLock is an example of a reentrant context manager, as are suppress() and redirect_stdout(). Here’s a very simple example of reentrant use: >>> from contextlib import redirect_stdout
>>> from io import StringIO
>>> stream = StringIO()
>>> write_to_stream = redirect_stdout(stream)
>>> with write_to_stream:
... print("This is written to the stream rather than stdout")
... with write_to_stream:
... print("This is also written to the stream")
...
>>> print("This is written directly to stdout")
This is written directly to stdout
>>> print(stream.getvalue())
This is written to the stream rather than stdout
This is also written to the stream
Real world examples of reentrancy are more likely to involve multiple functions calling each other and hence be far more complicated than this example. Note also that being reentrant is not the same thing as being thread safe. redirect_stdout(), for example, is definitely not thread safe, as it makes a global modification to the system state by binding sys.stdout to a different stream. Reusable context managers Distinct from both single use and reentrant context managers are “reusable” context managers (or, to be completely explicit, “reusable, but not reentrant” context managers, since reentrant context managers are also reusable). These context managers support being used multiple times, but will fail (or otherwise not work correctly) if the specific context manager instance has already been used in a containing with statement. threading.Lock is an example of a reusable, but not reentrant, context manager (for a reentrant lock, it is necessary to use threading.RLock instead). Another example of a reusable, but not reentrant, context manager is ExitStack, as it invokes all currently registered callbacks when leaving any with statement, regardless of where those callbacks were added: >>> from contextlib import ExitStack
>>> stack = ExitStack()
>>> with stack:
... stack.callback(print, "Callback: from first context")
... print("Leaving first context")
...
Leaving first context
Callback: from first context
>>> with stack:
... stack.callback(print, "Callback: from second context")
... print("Leaving second context")
...
Leaving second context
Callback: from second context
>>> with stack:
... stack.callback(print, "Callback: from outer context")
... with stack:
... stack.callback(print, "Callback: from inner context")
... print("Leaving inner context")
... print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Callback: from outer context
Leaving outer context
As the output from the example shows, reusing a single stack object across multiple with statements works correctly, but attempting to nest them will cause the stack to be cleared at the end of the innermost with statement, which is unlikely to be desirable behaviour. Using separate ExitStack instances instead of reusing a single instance avoids that problem: >>> from contextlib import ExitStack
>>> with ExitStack() as outer_stack:
... outer_stack.callback(print, "Callback: from outer context")
... with ExitStack() as inner_stack:
... inner_stack.callback(print, "Callback: from inner context")
... print("Leaving inner context")
... print("Leaving outer context")
...
Leaving inner context
Callback: from inner context
Leaving outer context
Callback: from outer context | python.library.contextlib |
class contextlib.AbstractAsyncContextManager
An abstract base class for classes that implement object.__aenter__() and object.__aexit__(). A default implementation for object.__aenter__() is provided which returns self while object.__aexit__() is an abstract method which by default returns None. See also the definition of Asynchronous Context Managers. New in version 3.7. | python.library.contextlib#contextlib.AbstractAsyncContextManager |
class contextlib.AbstractContextManager
An abstract base class for classes that implement object.__enter__() and object.__exit__(). A default implementation for object.__enter__() is provided which returns self while object.__exit__() is an abstract method which by default returns None. See also the definition of Context Manager Types. New in version 3.6. | python.library.contextlib#contextlib.AbstractContextManager |
@contextlib.asynccontextmanager
Similar to contextmanager(), but creates an asynchronous context manager. This function is a decorator that can be used to define a factory function for async with statement asynchronous context managers, without needing to create a class or separate __aenter__() and __aexit__() methods. It must be applied to an asynchronous generator function. A simple example: from contextlib import asynccontextmanager
@asynccontextmanager
async def get_connection():
conn = await acquire_db_connection()
try:
yield conn
finally:
await release_db_connection(conn)
async def get_all_users():
async with get_connection() as conn:
return conn.query('SELECT ...')
New in version 3.7. | python.library.contextlib#contextlib.asynccontextmanager |
class contextlib.AsyncExitStack
An asynchronous context manager, similar to ExitStack, that supports combining both synchronous and asynchronous context managers, as well as having coroutines for cleanup logic. The close() method is not implemented, aclose() must be used instead.
enter_async_context(cm)
Similar to enter_context() but expects an asynchronous context manager.
push_async_exit(exit)
Similar to push() but expects either an asynchronous context manager or a coroutine function.
push_async_callback(callback, /, *args, **kwds)
Similar to callback() but expects a coroutine function.
aclose()
Similar to close() but properly handles awaitables.
Continuing the example for asynccontextmanager(): async with AsyncExitStack() as stack:
connections = [await stack.enter_async_context(get_connection())
for i in range(5)]
# All opened connections will automatically be released at the end of
# the async with statement, even if attempts to open a connection
# later in the list raise an exception.
New in version 3.7. | python.library.contextlib#contextlib.AsyncExitStack |
aclose()
Similar to close() but properly handles awaitables. | python.library.contextlib#contextlib.AsyncExitStack.aclose |
enter_async_context(cm)
Similar to enter_context() but expects an asynchronous context manager. | python.library.contextlib#contextlib.AsyncExitStack.enter_async_context |
push_async_callback(callback, /, *args, **kwds)
Similar to callback() but expects a coroutine function. | python.library.contextlib#contextlib.AsyncExitStack.push_async_callback |
push_async_exit(exit)
Similar to push() but expects either an asynchronous context manager or a coroutine function. | python.library.contextlib#contextlib.AsyncExitStack.push_async_exit |
contextlib.closing(thing)
Return a context manager that closes thing upon completion of the block. This is basically equivalent to: from contextlib import contextmanager
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
And lets you write code like this: from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('http://www.python.org')) as page:
for line in page:
print(line)
without needing to explicitly close page. Even if an error occurs, page.close() will be called when the with block is exited. | python.library.contextlib#contextlib.closing |
class contextlib.ContextDecorator
A base class that enables a context manager to also be used as a decorator. Context managers inheriting from ContextDecorator have to implement __enter__ and __exit__ as normal. __exit__ retains its optional exception handling even when used as a decorator. ContextDecorator is used by contextmanager(), so you get this functionality automatically. Example of ContextDecorator: from contextlib import ContextDecorator
class mycontext(ContextDecorator):
def __enter__(self):
print('Starting')
return self
def __exit__(self, *exc):
print('Finishing')
return False
>>> @mycontext()
... def function():
... print('The bit in the middle')
...
>>> function()
Starting
The bit in the middle
Finishing
>>> with mycontext():
... print('The bit in the middle')
...
Starting
The bit in the middle
Finishing
This change is just syntactic sugar for any construct of the following form: def f():
with cm():
# Do stuff
ContextDecorator lets you instead write: @cm()
def f():
# Do stuff
It makes it clear that the cm applies to the whole function, rather than just a piece of it (and saving an indentation level is nice, too). Existing context managers that already have a base class can be extended by using ContextDecorator as a mixin class: from contextlib import ContextDecorator
class mycontext(ContextBaseClass, ContextDecorator):
def __enter__(self):
return self
def __exit__(self, *exc):
return False
Note As the decorated function must be able to be called multiple times, the underlying context manager must support use in multiple with statements. If this is not the case, then the original construct with the explicit with statement inside the function should be used. New in version 3.2. | python.library.contextlib#contextlib.ContextDecorator |
@contextlib.contextmanager
This function is a decorator that can be used to define a factory function for with statement context managers, without needing to create a class or separate __enter__() and __exit__() methods. While many objects natively support use in with statements, sometimes a resource needs to be managed that isn’t a context manager in its own right, and doesn’t implement a close() method for use with contextlib.closing An abstract example would be the following to ensure correct resource management: from contextlib import contextmanager
@contextmanager
def managed_resource(*args, **kwds):
# Code to acquire resource, e.g.:
resource = acquire_resource(*args, **kwds)
try:
yield resource
finally:
# Code to release resource, e.g.:
release_resource(resource)
>>> with managed_resource(timeout=3600) as resource:
... # Resource is released at the end of this block,
... # even if code in the block raises an exception
The function being decorated must return a generator-iterator when called. This iterator must yield exactly one value, which will be bound to the targets in the with statement’s as clause, if any. At the point where the generator yields, the block nested in the with statement is executed. The generator is then resumed after the block is exited. If an unhandled exception occurs in the block, it is reraised inside the generator at the point where the yield occurred. Thus, you can use a try…except…finally statement to trap the error (if any), or ensure that some cleanup takes place. If an exception is trapped merely in order to log it or to perform some action (rather than to suppress it entirely), the generator must reraise that exception. Otherwise the generator context manager will indicate to the with statement that the exception has been handled, and execution will resume with the statement immediately following the with statement. contextmanager() uses ContextDecorator so the context managers it creates can be used as decorators as well as in with statements. When used as a decorator, a new generator instance is implicitly created on each function call (this allows the otherwise “one-shot” context managers created by contextmanager() to meet the requirement that context managers support multiple invocations in order to be used as decorators). Changed in version 3.2: Use of ContextDecorator. | python.library.contextlib#contextlib.contextmanager |
class contextlib.ExitStack
A context manager that is designed to make it easy to programmatically combine other context managers and cleanup functions, especially those that are optional or otherwise driven by input data. For example, a set of files may easily be handled in a single with statement as follows: with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected. This stack model is used so that context managers that acquire their resources in their __init__ method (such as file objects) can be handled correctly. Since registered callbacks are invoked in the reverse order of registration, this ends up behaving as if multiple nested with statements had been used with the registered set of callbacks. This even extends to exception handling - if an inner callback suppresses or replaces an exception, then outer callbacks will be passed arguments based on that updated state. This is a relatively low level API that takes care of the details of correctly unwinding the stack of exit callbacks. It provides a suitable foundation for higher level context managers that manipulate the exit stack in application specific ways. New in version 3.3.
enter_context(cm)
Enters a new context manager and adds its __exit__() method to the callback stack. The return value is the result of the context manager’s own __enter__() method. These context managers may suppress exceptions just as they normally would if used directly as part of a with statement.
push(exit)
Adds a context manager’s __exit__() method to the callback stack. As __enter__ is not invoked, this method can be used to cover part of an __enter__() implementation with a context manager’s own __exit__() method. If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s __exit__() method and adds it directly to the callback stack. By returning true values, these callbacks can suppress exceptions the same way context manager __exit__() methods can. The passed in object is returned from the function, allowing this method to be used as a function decorator.
callback(callback, /, *args, **kwds)
Accepts an arbitrary callback function and arguments and adds it to the callback stack. Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). The passed in callback is returned from the function, allowing this method to be used as a function decorator.
pop_all()
Transfers the callback stack to a fresh ExitStack instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a with statement). For example, a group of files can be opened as an “all or nothing” operation as follows: with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Hold onto the close method, but don't call it yet.
close_files = stack.pop_all().close
# If opening any file fails, all previously opened files will be
# closed automatically. If all files are opened successfully,
# they will remain open even after the with statement ends.
# close_files() can then be invoked explicitly to close them all.
close()
Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred. | python.library.contextlib#contextlib.ExitStack |
callback(callback, /, *args, **kwds)
Accepts an arbitrary callback function and arguments and adds it to the callback stack. Unlike the other methods, callbacks added this way cannot suppress exceptions (as they are never passed the exception details). The passed in callback is returned from the function, allowing this method to be used as a function decorator. | python.library.contextlib#contextlib.ExitStack.callback |
close()
Immediately unwinds the callback stack, invoking callbacks in the reverse order of registration. For any context managers and exit callbacks registered, the arguments passed in will indicate that no exception occurred. | python.library.contextlib#contextlib.ExitStack.close |
enter_context(cm)
Enters a new context manager and adds its __exit__() method to the callback stack. The return value is the result of the context manager’s own __enter__() method. These context managers may suppress exceptions just as they normally would if used directly as part of a with statement. | python.library.contextlib#contextlib.ExitStack.enter_context |
pop_all()
Transfers the callback stack to a fresh ExitStack instance and returns it. No callbacks are invoked by this operation - instead, they will now be invoked when the new stack is closed (either explicitly or implicitly at the end of a with statement). For example, a group of files can be opened as an “all or nothing” operation as follows: with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Hold onto the close method, but don't call it yet.
close_files = stack.pop_all().close
# If opening any file fails, all previously opened files will be
# closed automatically. If all files are opened successfully,
# they will remain open even after the with statement ends.
# close_files() can then be invoked explicitly to close them all. | python.library.contextlib#contextlib.ExitStack.pop_all |
push(exit)
Adds a context manager’s __exit__() method to the callback stack. As __enter__ is not invoked, this method can be used to cover part of an __enter__() implementation with a context manager’s own __exit__() method. If passed an object that is not a context manager, this method assumes it is a callback with the same signature as a context manager’s __exit__() method and adds it directly to the callback stack. By returning true values, these callbacks can suppress exceptions the same way context manager __exit__() methods can. The passed in object is returned from the function, allowing this method to be used as a function decorator. | python.library.contextlib#contextlib.ExitStack.push |
contextlib.nullcontext(enter_result=None)
Return a context manager that returns enter_result from __enter__, but otherwise does nothing. It is intended to be used as a stand-in for an optional context manager, for example: def myfunction(arg, ignore_exceptions=False):
if ignore_exceptions:
# Use suppress to ignore all exceptions.
cm = contextlib.suppress(Exception)
else:
# Do not ignore any exceptions, cm has no effect.
cm = contextlib.nullcontext()
with cm:
# Do something
An example using enter_result: def process_file(file_or_path):
if isinstance(file_or_path, str):
# If string, open file
cm = open(file_or_path)
else:
# Caller is responsible for closing file
cm = nullcontext(file_or_path)
with cm as file:
# Perform processing on the file
New in version 3.7. | python.library.contextlib#contextlib.nullcontext |
contextlib.redirect_stderr(new_target)
Similar to redirect_stdout() but redirecting sys.stderr to another file or file-like object. This context manager is reentrant. New in version 3.5. | python.library.contextlib#contextlib.redirect_stderr |
contextlib.redirect_stdout(new_target)
Context manager for temporarily redirecting sys.stdout to another file or file-like object. This tool adds flexibility to existing functions or classes whose output is hardwired to stdout. For example, the output of help() normally is sent to sys.stdout. You can capture that output in a string by redirecting the output to an io.StringIO object: f = io.StringIO()
with redirect_stdout(f):
help(pow)
s = f.getvalue()
To send the output of help() to a file on disk, redirect the output to a regular file: with open('help.txt', 'w') as f:
with redirect_stdout(f):
help(pow)
To send the output of help() to sys.stderr: with redirect_stdout(sys.stderr):
help(pow)
Note that the global side effect on sys.stdout means that this context manager is not suitable for use in library code and most threaded applications. It also has no effect on the output of subprocesses. However, it is still a useful approach for many utility scripts. This context manager is reentrant. New in version 3.4. | python.library.contextlib#contextlib.redirect_stdout |
contextlib.suppress(*exceptions)
Return a context manager that suppresses any of the specified exceptions if they occur in the body of a with statement and then resumes execution with the first statement following the end of the with statement. As with any other mechanism that completely suppresses exceptions, this context manager should be used only to cover very specific errors where silently continuing with program execution is known to be the right thing to do. For example: from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
with suppress(FileNotFoundError):
os.remove('someotherfile.tmp')
This code is equivalent to: try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
try:
os.remove('someotherfile.tmp')
except FileNotFoundError:
pass
This context manager is reentrant. New in version 3.4. | python.library.contextlib#contextlib.suppress |
contextmanager.__enter__()
Enter the runtime context and return either this object or another object related to the runtime context. The value returned by this method is bound to the identifier in the as clause of with statements using this context manager. An example of a context manager that returns itself is a file object. File objects return themselves from __enter__() to allow open() to be used as the context expression in a with statement. An example of a context manager that returns a related object is the one returned by decimal.localcontext(). These managers set the active decimal context to a copy of the original decimal context and then return the copy. This allows changes to be made to the current decimal context in the body of the with statement without affecting code outside the with statement. | python.library.stdtypes#contextmanager.__enter__ |
contextmanager.__exit__(exc_type, exc_val, exc_tb)
Exit the runtime context and return a Boolean flag indicating if any exception that occurred should be suppressed. If an exception occurred while executing the body of the with statement, the arguments contain the exception type, value and traceback information. Otherwise, all three arguments are None. Returning a true value from this method will cause the with statement to suppress the exception and continue execution with the statement immediately following the with statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement. The exception passed in should never be reraised explicitly - instead, this method should return a false value to indicate that the method completed successfully and does not want to suppress the raised exception. This allows context management code to easily detect whether or not an __exit__() method has actually failed. | python.library.stdtypes#contextmanager.__exit__ |
contextvars — Context Variables This module provides APIs to manage, store, and access context-local state. The ContextVar class is used to declare and work with Context Variables. The copy_context() function and the Context class should be used to manage the current context in asynchronous frameworks. Context managers that have state should use Context Variables instead of threading.local() to prevent their state from bleeding to other code unexpectedly, when used in concurrent code. See also PEP 567 for additional details. New in version 3.7. Context Variables
class contextvars.ContextVar(name[, *, default])
This class is used to declare a new Context Variable, e.g.: var: ContextVar[int] = ContextVar('var', default=42)
The required name parameter is used for introspection and debug purposes. The optional keyword-only default parameter is returned by ContextVar.get() when no value for the variable is found in the current context. Important: Context Variables should be created at the top module level and never in closures. Context objects hold strong references to context variables which prevents context variables from being properly garbage collected.
name
The name of the variable. This is a read-only property. New in version 3.7.1.
get([default])
Return a value for the context variable for the current context. If there is no value for the variable in the current context, the method will: return the value of the default argument of the method, if provided; or return the default value for the context variable, if it was created with one; or raise a LookupError.
set(value)
Call to set a new value for the context variable in the current context. The required value argument is the new value for the context variable. Returns a Token object that can be used to restore the variable to its previous value via the ContextVar.reset() method.
reset(token)
Reset the context variable to the value it had before the ContextVar.set() that created the token was used. For example: var = ContextVar('var')
token = var.set('new value')
# code that uses 'var'; var.get() returns 'new value'.
var.reset(token)
# After the reset call the var has no value again, so
# var.get() would raise a LookupError.
class contextvars.Token
Token objects are returned by the ContextVar.set() method. They can be passed to the ContextVar.reset() method to revert the value of the variable to what it was before the corresponding set.
Token.var
A read-only property. Points to the ContextVar object that created the token.
Token.old_value
A read-only property. Set to the value the variable had before the ContextVar.set() method call that created the token. It points to Token.MISSING is the variable was not set before the call.
Token.MISSING
A marker object used by Token.old_value.
Manual Context Management
contextvars.copy_context()
Returns a copy of the current Context object. The following snippet gets a copy of the current context and prints all variables and their values that are set in it: ctx: Context = copy_context()
print(list(ctx.items()))
The function has an O(1) complexity, i.e. works equally fast for contexts with a few context variables and for contexts that have a lot of them.
class contextvars.Context
A mapping of ContextVars to their values. Context() creates an empty context with no values in it. To get a copy of the current context use the copy_context() function. Context implements the collections.abc.Mapping interface.
run(callable, *args, **kwargs)
Execute callable(*args, **kwargs) code in the context object the run method is called on. Return the result of the execution or propagate an exception if one occurred. Any changes to any context variables that callable makes will be contained in the context object: var = ContextVar('var')
var.set('spam')
def main():
# 'var' was set to 'spam' before
# calling 'copy_context()' and 'ctx.run(main)', so:
# var.get() == ctx[var] == 'spam'
var.set('ham')
# Now, after setting 'var' to 'ham':
# var.get() == ctx[var] == 'ham'
ctx = copy_context()
# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)
# The 'main()' function was run in the 'ctx' context,
# so changes to 'var' are contained in it:
# ctx[var] == 'ham'
# However, outside of 'ctx', 'var' is still set to 'spam':
# var.get() == 'spam'
The method raises a RuntimeError when called on the same context object from more than one OS thread, or when called recursively.
copy()
Return a shallow copy of the context object.
var in context
Return True if the context has a value for var set; return False otherwise.
context[var]
Return the value of the var ContextVar variable. If the variable is not set in the context object, a KeyError is raised.
get(var[, default])
Return the value for var if var has the value in the context object. Return default otherwise. If default is not given, return None.
iter(context)
Return an iterator over the variables stored in the context object.
len(proxy)
Return the number of variables set in the context object.
keys()
Return a list of all variables in the context object.
values()
Return a list of all variables’ values in the context object.
items()
Return a list of 2-tuples containing all variables and their values in the context object.
asyncio support Context variables are natively supported in asyncio and are ready to be used without any extra configuration. For example, here is a simple echo server, that uses a context variable to make the address of a remote client available in the Task that handles that client: import asyncio
import contextvars
client_addr_var = contextvars.ContextVar('client_addr')
def render_goodbye():
# The address of the currently handled client can be accessed
# without passing it explicitly to this function.
client_addr = client_addr_var.get()
return f'Good bye, client @ {client_addr}\n'.encode()
async def handle_request(reader, writer):
addr = writer.transport.get_extra_info('socket').getpeername()
client_addr_var.set(addr)
# In any code that we call is now possible to get
# client's address by calling 'client_addr_var.get()'.
while True:
line = await reader.readline()
print(line)
if not line.strip():
break
writer.write(line)
writer.write(render_goodbye())
writer.close()
async def main():
srv = await asyncio.start_server(
handle_request, '127.0.0.1', 8081)
async with srv:
await srv.serve_forever()
asyncio.run(main())
# To test it you can use telnet:
# telnet 127.0.0.1 8081 | python.library.contextvars |
class contextvars.Context
A mapping of ContextVars to their values. Context() creates an empty context with no values in it. To get a copy of the current context use the copy_context() function. Context implements the collections.abc.Mapping interface.
run(callable, *args, **kwargs)
Execute callable(*args, **kwargs) code in the context object the run method is called on. Return the result of the execution or propagate an exception if one occurred. Any changes to any context variables that callable makes will be contained in the context object: var = ContextVar('var')
var.set('spam')
def main():
# 'var' was set to 'spam' before
# calling 'copy_context()' and 'ctx.run(main)', so:
# var.get() == ctx[var] == 'spam'
var.set('ham')
# Now, after setting 'var' to 'ham':
# var.get() == ctx[var] == 'ham'
ctx = copy_context()
# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)
# The 'main()' function was run in the 'ctx' context,
# so changes to 'var' are contained in it:
# ctx[var] == 'ham'
# However, outside of 'ctx', 'var' is still set to 'spam':
# var.get() == 'spam'
The method raises a RuntimeError when called on the same context object from more than one OS thread, or when called recursively.
copy()
Return a shallow copy of the context object.
var in context
Return True if the context has a value for var set; return False otherwise.
context[var]
Return the value of the var ContextVar variable. If the variable is not set in the context object, a KeyError is raised.
get(var[, default])
Return the value for var if var has the value in the context object. Return default otherwise. If default is not given, return None.
iter(context)
Return an iterator over the variables stored in the context object.
len(proxy)
Return the number of variables set in the context object.
keys()
Return a list of all variables in the context object.
values()
Return a list of all variables’ values in the context object.
items()
Return a list of 2-tuples containing all variables and their values in the context object. | python.library.contextvars#contextvars.Context |
copy()
Return a shallow copy of the context object. | python.library.contextvars#contextvars.Context.copy |
get(var[, default])
Return the value for var if var has the value in the context object. Return default otherwise. If default is not given, return None. | python.library.contextvars#contextvars.Context.get |
items()
Return a list of 2-tuples containing all variables and their values in the context object. | python.library.contextvars#contextvars.Context.items |
keys()
Return a list of all variables in the context object. | python.library.contextvars#contextvars.Context.keys |
run(callable, *args, **kwargs)
Execute callable(*args, **kwargs) code in the context object the run method is called on. Return the result of the execution or propagate an exception if one occurred. Any changes to any context variables that callable makes will be contained in the context object: var = ContextVar('var')
var.set('spam')
def main():
# 'var' was set to 'spam' before
# calling 'copy_context()' and 'ctx.run(main)', so:
# var.get() == ctx[var] == 'spam'
var.set('ham')
# Now, after setting 'var' to 'ham':
# var.get() == ctx[var] == 'ham'
ctx = copy_context()
# Any changes that the 'main' function makes to 'var'
# will be contained in 'ctx'.
ctx.run(main)
# The 'main()' function was run in the 'ctx' context,
# so changes to 'var' are contained in it:
# ctx[var] == 'ham'
# However, outside of 'ctx', 'var' is still set to 'spam':
# var.get() == 'spam'
The method raises a RuntimeError when called on the same context object from more than one OS thread, or when called recursively. | python.library.contextvars#contextvars.Context.run |
values()
Return a list of all variables’ values in the context object. | python.library.contextvars#contextvars.Context.values |
class contextvars.ContextVar(name[, *, default])
This class is used to declare a new Context Variable, e.g.: var: ContextVar[int] = ContextVar('var', default=42)
The required name parameter is used for introspection and debug purposes. The optional keyword-only default parameter is returned by ContextVar.get() when no value for the variable is found in the current context. Important: Context Variables should be created at the top module level and never in closures. Context objects hold strong references to context variables which prevents context variables from being properly garbage collected.
name
The name of the variable. This is a read-only property. New in version 3.7.1.
get([default])
Return a value for the context variable for the current context. If there is no value for the variable in the current context, the method will: return the value of the default argument of the method, if provided; or return the default value for the context variable, if it was created with one; or raise a LookupError.
set(value)
Call to set a new value for the context variable in the current context. The required value argument is the new value for the context variable. Returns a Token object that can be used to restore the variable to its previous value via the ContextVar.reset() method.
reset(token)
Reset the context variable to the value it had before the ContextVar.set() that created the token was used. For example: var = ContextVar('var')
token = var.set('new value')
# code that uses 'var'; var.get() returns 'new value'.
var.reset(token)
# After the reset call the var has no value again, so
# var.get() would raise a LookupError. | python.library.contextvars#contextvars.ContextVar |
get([default])
Return a value for the context variable for the current context. If there is no value for the variable in the current context, the method will: return the value of the default argument of the method, if provided; or return the default value for the context variable, if it was created with one; or raise a LookupError. | python.library.contextvars#contextvars.ContextVar.get |
name
The name of the variable. This is a read-only property. New in version 3.7.1. | python.library.contextvars#contextvars.ContextVar.name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.