The import system

5. The import system¶
Python code in one module gains access to the code in another module
by the process of importing it. The import
statement is
the most common way of invoking the import machinery, but it is not the only
way. Functions such as importlib.import_module()
and built-in
__import__()
can also be used to invoke the import machinery.
The import
statement combines two operations; it searches for the
named module, then it binds the results of that search to a name in the local
scope. The search operation of the import
statement is defined as
a call to the __import__()
function, with the appropriate arguments.
The return value of __import__()
is used to perform the name
binding operation of the import
statement. See the
import
statement for the exact details of that name binding
operation.
A direct call to __import__()
performs only the module search and, if
found, the module creation operation. While certain side-effects may occur,
such as the importing of parent packages, and the updating of various caches
(including sys.modules
), only the import
statement performs
a name binding operation.
When an import
statement is executed, the standard builtin
__import__()
function is called. Other mechanisms for invoking the
import system (such as importlib.import_module()
) may choose to bypass
__import__()
and use their own solutions to implement import semantics.
When a module is first imported, Python searches for the module and if found,
it creates a module object [1], initializing it. If the named module
cannot be found, a ModuleNotFoundError
is raised. Python implements various
strategies to search for the named module when the import machinery is
invoked. These strategies can be modified and extended by using various hooks
described in the sections below.
Changed in version 3.3: The import system has been updated to fully implement the second phase
of PEP 302. There is no longer any implicit import machinery - the full
import system is exposed through sys.meta_path
. In addition,
native namespace package support has been implemented (see PEP 420).
5.1. importlib
¶
The importlib
module provides a rich API for interacting with the
import system. For example importlib.import_module()
provides a
recommended, simpler API than built-in __import__()
for invoking the
import machinery. Refer to the importlib
library documentation for
additional detail.
5.2. Packages¶
Python has only one type of module object, and all modules are of this type, regardless of whether the module is implemented in Python, C, or something else. To help organize modules and provide a naming hierarchy, Python has a concept of packages.
You can think of packages as the directories on a file system and modules as files within directories, but don’t take this analogy too literally since packages and modules need not originate from the file system. For the purposes of this documentation, we’ll use this convenient analogy of directories and files. Like file system directories, packages are organized hierarchically, and packages may themselves contain subpackages, as well as regular modules.
It’s important to keep in mind that all packages are modules, but not all
modules are packages. Or put another way, packages are just a special kind of
module. Specifically, any module that contains a __path__
attribute is
considered a package.
All modules have a name. Subpackage names are separated from their parent
package name by a dot, akin to Python’s standard attribute access syntax. Thus
you might have a package called email
, which in turn has a subpackage
called email.mime
and a module within that subpackage called
email.mime.text
.
5.2.1. Regular packages¶
Python defines two types of packages, regular packages and namespace packages. Regular
packages are traditional packages as they existed in Python 3.2 and earlier.
A regular package is typically implemented as a directory containing an
__init__.py
file. When a regular package is imported, this
__init__.py
file is implicitly executed, and the objects it defines are
bound to names in the package’s namespace. The __init__.py
file can
contain the same Python code that any other module can contain, and Python
will add some additional attributes to the module when it is imported.
For example, the following file system layout defines a top level parent
package with three subpackages:
parent/
__init__.py
one/
__init__.py
two/
__init__.py
three/
__init__.py
Importing parent.one
will implicitly execute parent/__init__.py
and
parent/one/__init__.py
. Subsequent imports of parent.two
or
parent.three
will execute parent/two/__init__.py
and
parent/three/__init__.py
respectively.
5.2.2. Namespace packages¶
A namespace package is a composite of various portions, where each portion contributes a subpackage to the parent package. Portions may reside in different locations on the file system. Portions may also be found in zip files, on the network, or anywhere else that Python searches during import. Namespace packages may or may not correspond directly to objects on the file system; they may be virtual modules that have no concrete representation.
Namespace packages do not use an ordinary list for their __path__
attribute. They instead use a custom iterable type which will automatically
perform a new search for package portions on the next import attempt within
that package if the path of their parent package (or sys.path
for a
top level package) changes.
With namespace packages, there is no parent/__init__.py
file. In fact,
there may be multiple parent
directories found during import search, where
each one is provided by a different portion. Thus parent/one
may not be
physically located next to parent/two
. In this case, Python will create a
namespace package for the top-level parent
package whenever it or one of
its subpackages is imported.
See also PEP 420 for the namespace package specification.
5.3. Searching¶
To begin the search, Python needs the fully qualified
name of the module (or package, but for the purposes of this discussion, the
difference is immaterial) being imported. This name may come from various
arguments to the import
statement, or from the parameters to the
importlib.import_module()
or __import__()
functions.
This name will be used in various phases of the import search, and it may be
the dotted path to a submodule, e.g. foo.bar.baz
. In this case, Python
first tries to import foo
, then foo.bar
, and finally foo.bar.baz
.
If any of the intermediate imports fail, a ModuleNotFoundError
is raised.
5.3.1. The module cache¶
The first place checked during import search is sys.modules
. This
mapping serves as a cache of all modules that have been previously imported,
including the intermediate paths. So if foo.bar.baz
was previously
imported, sys.modules
will contain entries for foo
, foo.bar
,
and foo.bar.baz
. Each key will have as its value the corresponding module
object.
During import, the module name is looked up in sys.modules
and if
present, the associated value is the module satisfying the import, and the
process completes. However, if the value is None
, then a
ModuleNotFoundError
is raised. If the module name is missing, Python will
continue searching for the module.
sys.modules
is writable. Deleting a key may not destroy the
associated module (as other modules may hold references to it),
but it will invalidate the cache entry for the named module, causing
Python to search anew for the named module upon its next
import. The key can also be assigned to None
, forcing the next import
of the module to result in a ModuleNotFoundError
.
Beware though, as if you keep a reference to the module object,
invalidate its cache entry in sys.modules
, and then re-import the
named module, the two module objects will not be the same. By contrast,
importlib.reload()
will reuse the same module object, and simply
reinitialise the module contents by rerunning the module’s code.
5.3.2. Finders and loaders¶
If the named module is not found in sys.modules
, then Python’s import
protocol is invoked to find and load the module. This protocol consists of
two conceptual objects, finders and loaders.
A finder’s job is to determine whether it can find the named module using
whatever strategy it knows about. Objects that implement both of these
interfaces are referred to as importers - they return
themselves when they find that they can load the requested module.
Python includes a number of default finders and importers. The first one knows how to locate built-in modules, and the second knows how to locate frozen modules. A third default finder searches an import path for modules. The import path is a list of locations that may name file system paths or zip files. It can also be extended to search for any locatable resource, such as those identified by URLs.
The import machinery is extensible, so new finders can be added to extend the range and scope of module searching.
Finders do not actually load modules. If they can find the named module, they return a module spec, an encapsulation of the module’s import-related information, which the import machinery then uses when loading the module.
The following sections describe the protocol for finders and loaders in more detail, including how you can create and register new ones to extend the import machinery.
Changed in version 3.4: In previous versions of Python, finders returned loaders directly, whereas now they return module specs which contain loaders. Loaders are still used during import but have fewer responsibilities.
5.3.3. Import hooks¶
The import machinery is designed to be extensible; the primary mechanism for this are the import hooks. There are two types of import hooks: meta hooks and import path hooks.
Meta hooks are called at the start of import processing, before any other
import processing has occurred, other than sys.modules
cache look up.
This allows meta hooks to override sys.path
processing, frozen
modules, or even built-in modules. Meta hooks are registered by adding new
finder objects to sys.meta_path
, as described below.
Import path hooks are called as part of sys.path
(or
package.__path__
) processing, at the point where their associated path
item is encountered. Import path hooks are registered by adding new callables
to sys.path_hooks
as described below.
5.3.4. The meta path¶
When the named module is not found in sys.modules
, Python next
searches sys.meta_path
, which contains a list of meta path finder
objects. These finders are queried in order to see if they know how to handle
the named module. Meta path finders must implement a method called
find_spec()
which takes three arguments:
a name, an import path, and (optionally) a target module. The meta path
finder can use any strategy it wants to determine whether it can handle
the named module or not.
If the meta path finder knows how to handle the named module, it returns a
spec object. If it cannot handle the named module, it returns None
. If
sys.meta_path
processing reaches the end of its list without returning
a spec, then a ModuleNotFoundError
is raised. Any other exceptions
raised are simply propagated up, aborting the import process.
The find_spec()
method of meta path
finders is called with two or three arguments. The first is the fully
qualified name of the module being imported, for example foo.bar.baz
.
The second argument is the path entries to use for the module search. For
top-level modules, the second argument is None
, but for submodules or
subpackages, the second argument is the value of the parent package’s
__path__
attribute. If the appropriate __path__
attribute cannot
be accessed, a ModuleNotFoundError
is raised. The third argument
is an existing module object that will be the target of loading later.
The import system passes in a target module only during reload.
The meta path may be traversed multiple times for a single import request.
For example, assuming none of the modules involved has already been cached,
importing foo.bar.baz
will first perform a top level import, calling
mpf.find_spec("foo", None, None)
on each meta path finder (mpf
). After
foo
has been imported, foo.bar
will be imported by traversing the
meta path a second time, calling
mpf.find_spec("foo.bar", foo.__path__, None)
. Once foo.bar
has been
imported, the final traversal will call
mpf.find_spec("foo.bar.baz", foo.bar.__path__, None)
.
Some meta path finders only support top level imports. These importers will
always return None
when anything other than None
is passed as the
second argument.
Python’s default sys.meta_path
has three meta path finders, one that
knows how to import built-in modules, one that knows how to import frozen
modules, and one that knows how to import modules from an import path
(i.e. the path based finder).
Changed in version 3.4: The find_spec()
method of meta path
finders replaced find_module()
, which
is now deprecated. While it will continue to work without change, the
import machinery will try it only if the finder does not implement
find_spec()
.
Changed in version 3.10: Use of find_module()
by the import system
now raises ImportWarning
.
Changed in version 3.12: find_module()
has been removed.
Use find_spec()
instead.
5.4. Loading¶
If and when a module spec is found, the import machinery will use it (and the loader it contains) when loading the module. Here is an approximation of what happens during the loading portion of import:
module = None
if spec.loader is not None and hasattr(spec.loader, 'create_module'):
# It is assumed 'exec_module' will also be defined on the loader.
module = spec.loader.create_module(spec)
if module is None:
module = ModuleType(spec.name)
# The import-related module attributes get set here:
_init_module_attrs(spec, module)
if spec.loader is None:
# unsupported
raise ImportError
if spec.origin is None and spec.submodule_search_locations is not None:
# namespace package
sys.modules[spec.name] = module
elif not hasattr(spec.loader, 'exec_module'):
module = spec.loader.load_module(spec.name)
else:
sys.modules[spec.name] = module
try:
spec.loader.exec_module(module)
except BaseException:
try:
del sys.modules[spec.name]
except KeyError:
pass
raise
return sys.modules[spec.name]
Note the following details:
If there is an existing module object with the given name in
sys.modules
, import will have already returned it.The module will exist in
sys.modules
before the loader executes the module code. This is crucial because the module code may (directly or indirectly) import itself; adding it tosys.modules
beforehand prevents unbounded recursion in the worst case and multiple loading in the best.If loading fails, the failing module – and only the failing module – gets removed from
sys.modules
. Any module already in thesys.modules
cache, and any module that was successfully loaded as a side-effect, must remain in the cache. This contrasts with reloading where even the failing module is left insys.modules
.After the module is created but before execution, the import machinery sets the import-related module attributes (“_init_module_attrs” in the pseudo-code example above), as summarized in a later section.
Module execution is the key moment of loading in which the module’s namespace gets populated. Execution is entirely delegated to the loader, which gets to decide what gets populated and how.
The module created during loading and passed to exec_module() may not be the one returned at the end of import [2].
Changed in version 3.4: The import system has taken over the boilerplate responsibilities of
loaders. These were previously performed by the
importlib.abc.Loader.load_module()
method.
5.4.1. Loaders¶
Module loaders provide the critical function of loading: module execution.
The import machinery calls the importlib.abc.Loader.exec_module()
method with a single argument, the module object to execute. Any value
returned from exec_module()
is ignored.
Loaders must satisfy the following requirements:
If the module is a Python module (as opposed to a built-in module or a dynamically loaded extension), the loader should execute the module’s code in the module’s global name space (
module.__dict__
).If the loader cannot execute the module, it should raise an
ImportError
, although any other exception raised duringexec_module()
will be propagated.
In many cases, the finder and loader can be the same object; in such cases the
find_spec()
method would just return a
spec with the loader set to self
.
Module loaders may opt in to creating the module object during loading
by implementing a create_module()
method.
It takes one argument, the module spec, and returns the new module object
to use during loading. create_module()
does not need to set any attributes
on the module object. If the method returns None
, the
import machinery will create the new module itself.
Added in version 3.4: The create_module()
method of loaders.
Changed in version 3.4: The load_module()
method was replaced by
exec_module()
and the import
machinery assumed all the boilerplate responsibilities of loading.
For compatibility with existing loaders, the import machinery will use
the load_module()
method of loaders if it exists and the loader does
not also implement exec_module()
. However, load_module()
has been
deprecated and loaders should implement exec_module()
instead.
The load_module()
method must implement all the boilerplate loading
functionality described above in addition to executing the module. All
the same constraints apply, with some additional clarification:
If there is an existing module object with the given name in
sys.modules
, the loader must use that existing module. (Otherwise,importlib.reload()
will not work correctly.) If the named module does not exist insys.modules
, the loader must create a new module object and add it tosys.modules
.The module must exist in
sys.modules
before the loader executes the module code, to prevent unbounded recursion or multiple loading.If loading fails, the loader must remove any modules it has inserted into
sys.modules
, but it must remove only the failing module(s), and only if the loader itself has loaded the module(s) explicitly.
Changed in version 3.5: A DeprecationWarning
is raised when exec_module()
is defined but
create_module()
is not.
Changed in version 3.6: An ImportError
is raised when exec_module()
is defined but
create_module()
is not.
Changed in version 3.10: Use of load_module()
will raise ImportWarning
.
5.4.2. Submodules¶
When a submodule is loaded using any mechanism (e.g. importlib
APIs, the
import
or import-from
statements, or built-in __import__()
) a
binding is placed in the parent module’s namespace to the submodule object.
For example, if package spam
has a submodule foo
, after importing
spam.foo
, spam
will have an attribute foo
which is bound to the
submodule. Let’s say you have the following directory structure:
spam/
__init__.py
foo.py
and spam/__init__.py
has the following line in it:
from .foo import Foo
then executing the following puts name bindings for foo
and Foo
in the
spam
module:
>>> import spam
>>> spam.foo
<module 'spam.foo' from '/tmp/imports/spam/foo.py'>
>>> spam.Foo
<class 'spam.foo.Foo'>
Given Python’s familiar name binding rules this might seem surprising, but
it’s actually a fundamental feature of the import system. The invariant
holding is that if you have sys.modules['spam']
and
sys.modules['spam.foo']
(as you would after the above import), the latter
must appear as the foo
attribute of the former.
5.4.3. Module specs¶
The import machinery uses a variety of information about each module during import, especially before loading. Most of the information is common to all modules. The purpose of a module’s spec is to encapsulate this import-related information on a per-module basis.
Using a spec during import allows state to be transferred between import system components, e.g. between the finder that creates the module spec and the loader that executes it. Most importantly, it allows the import machinery to perform the boilerplate operations of loading, whereas without a module spec the loader had that responsibility.
The module’s spec is exposed as module.__spec__
. Setting
__spec__
appropriately applies equally to
modules initialized during interpreter startup.
The one exception is __main__
, where __spec__
is
set to None in some cases.
See ModuleSpec
for details on the contents of
the module spec.
Added in version 3.4.
5.4.4. __path__ attributes on modules¶
The __path__
attribute should be a (possibly empty)
sequence of strings enumerating the locations where the package’s
submodules will be found. By definition, if a module has a __path__
attribute, it is a package.
A package’s __path__
attribute is used during imports of its
subpackages.
Within the import machinery, it functions much the same as sys.path
,
i.e. providing a list of locations to search for modules during import.
However, __path__
is typically much more constrained than
sys.path
.
The same rules used for sys.path
also apply to a package’s
__path__
. sys.path_hooks
(described below) are
consulted when traversing a package’s __path__
.
A package’s __init__.py
file may set or alter the package’s
__path__
attribute, and this was typically the way namespace packages were implemented
prior to PEP 420. With the adoption of PEP 420, namespace packages no
longer need to supply __init__.py
files containing only __path__
manipulation code; the import machinery automatically sets __path__
correctly for the namespace package.
5.4.5. Module reprs¶
By default, all modules have a usable repr, however depending on the attributes set above, and in the module’s spec, you can more explicitly control the repr of module objects.
If the module has a spec (__spec__
), the import machinery will try
to generate a repr from it. If that fails or there is no spec, the import
system will craft a default repr using whatever information is available
on the module. It will try to use the module.__name__
,
module.__file__
, and module.__loader__
as input into the repr,
with defaults for whatever information is missing.
Here are the exact rules used:
If the module has a
__spec__
attribute, the information in the spec is used to generate the repr. The “name”, “loader”, “origin”, and “has_location” attributes are consulted.If the module has a
__file__
attribute, this is used as part of the module’s repr.If the module has no
__file__
but does have a__loader__
that is notNone
, then the loader’s repr is used as part of the module’s repr.Otherwise, just use the module’s
__name__
in the repr.
Changed in version 3.12: Use of module_repr()
, having been deprecated since Python 3.4, was
removed in Python 3.12 and is no longer called during the resolution of a
module’s repr.
5.4.6. Cached bytecode invalidation¶
Before Python loads cached bytecode from a .pyc
file, it checks whether the
cache is up-to-date with the source .py
file. By default, Python does this
by storing the source’s last-modified timestamp and size in the cache file when
writing it. At runtime, the import system then validates the cache file by
checking the stored metadata in the cache file against the source’s
metadata.
Python also supports “hash-based” cache files, which store a hash of the source
file’s contents rather than its metadata. There are two variants of hash-based
.pyc
files: checked and unchecked. For checked hash-based .pyc
files,
Python validates the cache file by hashing the source file and comparing the
resulting hash with the hash in the cache file. If a checked hash-based cache
file is found to be invalid, Python regenerates it and writes a new checked
hash-based cache file. For unchecked hash-based .pyc
files, Python simply
assumes the cache file is valid if it exists. Hash-based .pyc
files
validation behavior may be overridden with the --check-hash-based-pycs
flag.
Changed in version 3.7: Added hash-based .pyc
files. Previously, Python only supported
timestamp-based invalidation of bytecode caches.
5.5. The Path Based Finder¶
As mentioned previously, Python comes with several default meta path finders.
One of these, called the path based finder
(PathFinder
), searches an import path,
which contains a list of path entries. Each path
entry names a location to search for modules.
The path based finder itself doesn’t know how to import anything. Instead, it traverses the individual path entries, associating each of them with a path entry finder that knows how to handle that particular kind of path.
The default set of path entry finders implement all the semantics for finding
modules on the file system, handling special file types such as Python source
code (.py
files), Python byte code (.pyc
files) and
shared libraries (e.g. .so
files). When supported by the zipimport
module in the standard library, the default path entry finders also handle
loading all of these file types (other than shared libraries) from zipfiles.
Path entries need not be limited to file system locations. They can refer to URLs, database queries, or any other location that can be specified as a string.
The path based finder provides additional hooks and protocols so that you can extend and customize the types of searchable path entries. For example, if you wanted to support path entries as network URLs, you could write a hook that implements HTTP semantics to find modules on the web. This hook (a callable) would return a path entry finder supporting the protocol described below, which was then used to get a loader for the module from the web.
A word of warning: this section and the previous both use the term finder,
distinguishing between them by using the terms meta path finder and
path entry finder. These two types of finders are very similar,
support similar protocols, and function in similar ways during the import
process, but it’s important to keep in mind that they are subtly different.
In particular, meta path finders operate at the beginning of the import
process, as keyed off the sys.meta_path
traversal.
By contrast, path entry finders are in a sense an implementation detail
of the path based finder, and in fact, if the path based finder were to be
removed from sys.meta_path
, none of the path entry finder semantics
would be invoked.
5.5.1. Path entry finders¶
The path based finder is responsible for finding and loading Python modules and packages whose location is specified with a string path entry. Most path entries name locations in the file system, but they need not be limited to this.
As a meta path finder, the path based finder implements the
find_spec()
protocol previously
described, however it exposes additional hooks that can be used to
customize how modules are found and loaded from the import path.
Three variables are used by the path based finder, sys.path
,
sys.path_hooks
and sys.path_importer_cache
. The __path__
attributes on package objects are also used. These provide additional ways
that the import machinery can be customized.
sys.path
contains a list of strings providing search locations for
modules and packages. It is initialized from the PYTHONPATH
environment variable and various other installation- and
implementation-specific defaults. Entries in sys.path
can name
directories on the file system, zip files, and potentially other “locations”
(see the site
module) that should be searched for modules, such as
URLs, or database queries. Only strings should be present on
sys.path
; all other data types are ignored.
The path based finder is a meta path finder, so the import
machinery begins the import path search by calling the path
based finder’s find_spec()
method as
described previously. When the path
argument to
find_spec()
is given, it will be a
list of string paths to traverse - typically a package’s __path__
attribute for an import within that package. If the path
argument is
None
, this indicates a top level import and sys.path
is used.
The path based finder iterates over every entry in the search path, and
for each of these, looks for an appropriate path entry finder
(PathEntryFinder
) for the
path entry. Because this can be an expensive operation (e.g. there may be
stat()
call overheads for this search), the path based finder maintains
a cache mapping path entries to path entry finders. This cache is maintained
in sys.path_importer_cache
(despite the name, this cache actually
stores finder objects rather than being limited to importer objects).
In this way, the expensive search for a particular path entry
location’s path entry finder need only be done once. User code is
free to remove cache entries from sys.path_importer_cache
forcing
the path based finder to perform the path entry search again.
If the path entry is not present in the cache, the path based finder iterates
over every callable in sys.path_hooks
. Each of the path entry
hooks in this list is called with a single argument, the
path entry to be searched. This callable may either return a path
entry finder that can handle the path entry, or it may raise
ImportError
. An ImportError
is used by the path based finder to
signal that the hook cannot find a path entry finder
for that path entry. The
exception is ignored and import path iteration continues. The hook
should expect either a string or bytes object; the encoding of bytes objects
is up to the hook (e.g. it may be a file system encoding, UTF-8, or something
else), and if the hook cannot decode the argument, it should raise
ImportError
.
If sys.path_hooks
iteration ends with no path entry finder
being returned, then the path based finder’s
find_spec()
method will store None
in sys.path_importer_cache
(to indicate that there is no finder for
this path entry) and return None
, indicating that this
meta path finder could not find the module.
If a path entry finder is returned by one of the path entry
hook callables on sys.path_hooks
, then the following protocol is used
to ask the finder for a module spec, which is then used when loading the
module.
The current working directory – denoted by an empty string – is handled
slightly differently from other entries on sys.path
. First, if the
current working directory cannot be determined or is found not to exist, no
value is stored in sys.path_importer_cache
. Second, the value for the
current working directory is looked up fresh for each module lookup. Third,
the path used for sys.path_importer_cache
and returned by
importlib.machinery.PathFinder.find_spec()
will be the actual current
working directory and not the empty string.
5.5.2. Path entry finder protocol¶
In order to support imports of modules and initialized packages and also to
contribute portions to namespace packages, path entry finders must implement
the find_spec()
method.
find_spec()
takes two arguments: the
fully qualified name of the module being imported, and the (optional) target
module. find_spec()
returns a fully populated spec for the module.
This spec will always have “loader” set (with one exception).
To indicate to the import machinery that the spec represents a namespace
portion, the path entry finder sets submodule_search_locations
to
a list containing the portion.
Changed in version 3.4: find_spec()
replaced
find_loader()
and
find_module()
, both of which
are now deprecated, but will be used if find_spec()
is not defined.
Older path entry finders may implement one of these two deprecated methods
instead of find_spec()
. The methods are still respected for the
sake of backward compatibility. However, if find_spec()
is
implemented on the path entry finder, the legacy methods are ignored.
find_loader()
takes one argument, the
fully qualified name of the module being imported. find_loader()
returns a 2-tuple where the first item is the loader and the second item
is a namespace portion.
For backwards compatibility with other implementations of the import
protocol, many path entry finders also support the same,
traditional find_module()
method that meta path finders support.
However path entry finder find_module()
methods are never called
with a path
argument (they are expected to record the appropriate
path information from the initial call to the path hook).
The find_module()
method on path entry finders is deprecated,
as it does not allow the path entry finder to contribute portions to
namespace packages. If both find_loader()
and find_module()
exist on a path entry finder, the import system will always call
find_loader()
in preference to find_module()
.
Changed in version 3.10: Calls to find_module()
and
find_loader()
by the import
system will raise ImportWarning
.
Changed in version 3.12: find_module()
and find_loader()
have been removed.
5.6. Replacing the standard import system¶
The most reliable mechanism for replacing the entire import system is to
delete the default contents of sys.meta_path
, replacing them
entirely with a custom meta path hook.
If it is acceptable to only alter the behaviour of import statements
without affecting other APIs that access the import system, then replacing
the builtin __import__()
function may be sufficient.
To selectively prevent the import of some modules from a hook early on the
meta path (rather than disabling the standard import system entirely),
it is sufficient to raise ModuleNotFoundError
directly from
find_spec()
instead of returning
None
. The latter indicates that the meta path search should continue,
while raising an exception terminates it immediately.
5.7. Package Relative Imports¶
Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first. For example, given the following package layout:
package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
subpackage2/
__init__.py
moduleZ.py
moduleA.py
In either subpackage1/moduleX.py
or subpackage1/__init__.py
,
the following are valid relative imports:
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
Absolute imports may use either the import <>
or from <> import <>
syntax, but relative imports may only use the second form; the reason
for this is that:
import XXX.YYY.ZZZ
should expose XXX.YYY.ZZZ
as a usable expression, but .moduleY is
not a valid expression.
5.8. Special considerations for __main__¶
The __main__
module is a special case relative to Python’s import
system. As noted elsewhere, the __main__
module
is directly initialized at interpreter startup, much like sys
and
builtins
. However, unlike those two, it doesn’t strictly
qualify as a built-in module. This is because the manner in which
__main__
is initialized depends on the flags and other options with
which the interpreter is invoked.
5.8.1. __main__.__spec__¶
Depending on how __main__
is initialized, __main__.__spec__
gets set appropriately or to None
.
When Python is started with the -m
option, __spec__
is set
to the module spec of the corresponding module or package. __spec__
is
also populated when the __main__
module is loaded as part of executing a
directory, zipfile or other sys.path
entry.
In the remaining cases
__main__.__spec__
is set to None
, as the code used to populate the
__main__
does not correspond directly with an importable module:
interactive prompt
-c
optionrunning from stdin
running directly from a source or bytecode file
Note that __main__.__spec__
is always None
in the last case,
even if the file could technically be imported directly as a module
instead. Use the -m
switch if valid module metadata is desired
in __main__
.
Note also that even when __main__
corresponds with an importable module
and __main__.__spec__
is set accordingly, they’re still considered
distinct modules. This is due to the fact that blocks guarded by
if __name__ == "__main__":
checks only execute when the module is used
to populate the __main__
namespace, and not during normal import.
5.9. References¶
The import machinery has evolved considerably since Python’s early days. The original specification for packages is still available to read, although some details have changed since the writing of that document.
The original specification for sys.meta_path
was PEP 302, with
subsequent extension in PEP 420.
PEP 420 introduced namespace packages for
Python 3.3. PEP 420 also introduced the find_loader()
protocol as an
alternative to find_module()
.
PEP 366 describes the addition of the __package__
attribute for
explicit relative imports in main modules.
PEP 328 introduced absolute and explicit relative imports and initially
proposed __name__
for semantics PEP 366 would eventually specify for
__package__
.
PEP 338 defines executing modules as scripts.
PEP 451 adds the encapsulation of per-module import state in spec objects. It also off-loads most of the boilerplate responsibilities of loaders back onto the import machinery. These changes allow the deprecation of several APIs in the import system and also addition of new methods to finders and loaders.
Footnotes


Search

Please activate JavaScript to enable the search functionality.
Searching for multiple words only shows matches that contain all words.


Descriptor Guide¶
- Author:
Raymond Hettinger
- Contact:
<python at rcn dot com>
Descriptors let objects customize attribute lookup, storage, and deletion.
This guide has four major sections:
The “primer” gives a basic overview, moving gently from simple examples, adding one feature at a time. Start here if you’re new to descriptors.
The second section shows a complete, practical descriptor example. If you already know the basics, start there.
The third section provides a more technical tutorial that goes into the detailed mechanics of how descriptors work. Most people don’t need this level of detail.
The last section has pure Python equivalents for built-in descriptors that are written in C. Read this if you’re curious about how functions turn into bound methods or about the implementation of common tools like
classmethod()
,staticmethod()
,property()
, and __slots__.
Primer¶
In this primer, we start with the most basic possible example and then we’ll add new capabilities one by one.
Simple example: A descriptor that returns a constant¶
The Ten
class is a descriptor whose __get__()
method always
returns the constant 10
:
class Ten:
def __get__(self, obj, objtype=None):
return 10
To use the descriptor, it must be stored as a class variable in another class:
class A:
x = 5 # Regular class attribute
y = Ten() # Descriptor instance
An interactive session shows the difference between normal attribute lookup and descriptor lookup:
>>> a = A() # Make an instance of class A
>>> a.x # Normal attribute lookup
5
>>> a.y # Descriptor lookup
10
In the a.x
attribute lookup, the dot operator finds 'x': 5
in the class dictionary. In the a.y
lookup, the dot operator
finds a descriptor instance, recognized by its __get__
method.
Calling that method returns 10
.
Note that the value 10
is not stored in either the class dictionary or the
instance dictionary. Instead, the value 10
is computed on demand.
This example shows how a simple descriptor works, but it isn’t very useful. For retrieving constants, normal attribute lookup would be better.
In the next section, we’ll create something more useful, a dynamic lookup.
Dynamic lookups¶
Interesting descriptors typically run computations instead of returning constants:
import os
class DirectorySize:
def __get__(self, obj, objtype=None):
return len(os.listdir(obj.dirname))
class Directory:
size = DirectorySize() # Descriptor instance
def __init__(self, dirname):
self.dirname = dirname # Regular instance attribute
An interactive session shows that the lookup is dynamic — it computes different, updated answers each time:
>>> s = Directory('songs')
>>> g = Directory('games')
>>> s.size # The songs directory has twenty files
20
>>> g.size # The games directory has three files
3
>>> os.remove('games/chess') # Delete a game
>>> g.size # File count is automatically updated
2
Besides showing how descriptors can run computations, this example also
reveals the purpose of the parameters to __get__()
. The self
parameter is size, an instance of DirectorySize. The obj parameter is
either g or s, an instance of Directory. It is the obj parameter that
lets the __get__()
method learn the target directory. The objtype
parameter is the class Directory.
Managed attributes¶
A popular use for descriptors is managing access to instance data. The
descriptor is assigned to a public attribute in the class dictionary while the
actual data is stored as a private attribute in the instance dictionary. The
descriptor’s __get__()
and __set__()
methods are triggered when
the public attribute is accessed.
In the following example, age is the public attribute and _age is the private attribute. When the public attribute is accessed, the descriptor logs the lookup or update:
import logging
logging.basicConfig(level=logging.INFO)
class LoggedAgeAccess:
def __get__(self, obj, objtype=None):
value = obj._age
logging.info('Accessing %r giving %r', 'age', value)
return value
def __set__(self, obj, value):
logging.info('Updating %r to %r', 'age', value)
obj._age = value
class Person:
age = LoggedAgeAccess() # Descriptor instance
def __init__(self, name, age):
self.name = name # Regular instance attribute
self.age = age # Calls __set__()
def birthday(self):
self.age += 1 # Calls both __get__() and __set__()
An interactive session shows that all access to the managed attribute age is logged, but that the regular attribute name is not logged:
>>> mary = Person('Mary M', 30) # The initial age update is logged
INFO:root:Updating 'age' to 30
>>> dave = Person('David D', 40)
INFO:root:Updating 'age' to 40
>>> vars(mary) # The actual data is in a private attribute
{'name': 'Mary M', '_age': 30}
>>> vars(dave)
{'name': 'David D', '_age': 40}
>>> mary.age # Access the data and log the lookup
INFO:root:Accessing 'age' giving 30
30
>>> mary.birthday() # Updates are logged as well
INFO:root:Accessing 'age' giving 30
INFO:root:Updating 'age' to 31
>>> dave.name # Regular attribute lookup isn't logged
'David D'
>>> dave.age # Only the managed attribute is logged
INFO:root:Accessing 'age' giving 40
40
One major issue with this example is that the private name _age is hardwired in the LoggedAgeAccess class. That means that each instance can only have one logged attribute and that its name is unchangeable. In the next example, we’ll fix that problem.
Customized names¶
When a class uses descriptors, it can inform each descriptor about which variable name was used.
In this example, the Person
class has two descriptor instances,
name and age. When the Person
class is defined, it makes a
callback to __set_name__()
in LoggedAccess so that the field names can
be recorded, giving each descriptor its own public_name and private_name:
import logging
logging.basicConfig(level=logging.INFO)
class LoggedAccess:
def __set_name__(self, owner, name):
self.public_name = name
self.private_name = '_' + name
def __get__(self, obj, objtype=None):
value = getattr(obj, self.private_name)
logging.info('Accessing %r giving %r', self.public_name, value)
return value
def __set__(self, obj, value):
logging.info('Updating %r to %r', self.public_name, value)
setattr(obj, self.private_name, value)
class Person:
name = LoggedAccess() # First descriptor instance
age = LoggedAccess() # Second descriptor instance
def __init__(self, name, age):
self.name = name # Calls the first descriptor
self.age = age # Calls the second descriptor
def birthday(self):
self.age += 1
An interactive session shows that the Person
class has called
__set_name__()
so that the field names would be recorded. Here
we call vars()
to look up the descriptor without triggering it:
>>> vars(vars(Person)['name'])
{'public_name': 'name', 'private_name': '_name'}
>>> vars(vars(Person)['age'])
{'public_name': 'age', 'private_name': '_age'}
The new class now logs access to both name and age:
>>> pete = Person('Peter P', 10)
INFO:root:Updating 'name' to 'Peter P'
INFO:root:Updating 'age' to 10
>>> kate = Person('Catherine C', 20)
INFO:root:Updating 'name' to 'Catherine C'
INFO:root:Updating 'age' to 20
The two Person instances contain only the private names:
>>> vars(pete)
{'_name': 'Peter P', '_age': 10}
>>> vars(kate)
{'_name': 'Catherine C', '_age': 20}
Closing thoughts¶
A descriptor is what we call any object that defines __get__()
,
__set__()
, or __delete__()
.
Optionally, descriptors can have a __set_name__()
method. This is only
used in cases where a descriptor needs to know either the class where it was
created or the name of class variable it was assigned to. (This method, if
present, is called even if the class is not a descriptor.)
Descriptors get invoked by the dot operator during attribute lookup. If a
descriptor is accessed indirectly with vars(some_class)[descriptor_name]
,
the descriptor instance is returned without invoking it.
Descriptors only work when used as class variables. When put in instances, they have no effect.
The main motivation for descriptors is to provide a hook allowing objects stored in class variables to control what happens during attribute lookup.
Traditionally, the calling class controls what happens during lookup. Descriptors invert that relationship and allow the data being looked-up to have a say in the matter.
Descriptors are used throughout the language. It is how functions turn into
bound methods. Common tools like classmethod()
, staticmethod()
,
property()
, and functools.cached_property()
are all implemented as
descriptors.
Complete Practical Example¶
In this example, we create a practical and powerful tool for locating notoriously hard to find data corruption bugs.
Validator class¶
A validator is a descriptor for managed attribute access. Prior to storing any data, it verifies that the new value meets various type and range restrictions. If those restrictions aren’t met, it raises an exception to prevent data corruption at its source.
This Validator
class is both an abstract base class and a
managed attribute descriptor:
from abc import ABC, abstractmethod
class Validator(ABC):
def __set_name__(self, owner, name):
self.private_name = '_' + name
def __get__(self, obj, objtype=None):
return getattr(obj, self.private_name)
def __set__(self, obj, value):
self.validate(value)
setattr(obj, self.private_name, value)
@abstractmethod
def validate(self, value):
pass
Custom validators need to inherit from Validator
and must supply a
validate()
method to test various restrictions as needed.
Custom validators¶
Here are three practical data validation utilities:
OneOf
verifies that a value is one of a restricted set of options.Number
verifies that a value is either anint
orfloat
. Optionally, it verifies that a value is between a given minimum or maximum.String
verifies that a value is astr
. Optionally, it validates a given minimum or maximum length. It can validate a user-defined predicate as well.
class OneOf(Validator):
def __init__(self, *options):
self.options = set(options)
def validate(self, value):
if value not in self.options:
raise ValueError(
f'Expected {value!r} to be one of {self.options!r}'
)
class Number(Validator):
def __init__(self, minvalue=None, maxvalue=None):
self.minvalue = minvalue
self.maxvalue = maxvalue
def validate(self, value):
if not isinstance(value, (int, float)):
raise TypeError(f'Expected {value!r} to be an int or float')
if self.minvalue is not None and value < self.minvalue:
raise ValueError(
f'Expected {value!r} to be at least {self.minvalue!r}'
)
if self.maxvalue is not None and value > self.maxvalue:
raise ValueError(
f'Expected {value!r} to be no more than {self.maxvalue!r}'
)
class String(Validator):
def __init__(self, minsize=None, maxsize=None, predicate=None):
self.minsize = minsize
self.maxsize = maxsize
self.predicate = predicate
def validate(self, value):
if not isinstance(value, str):
raise TypeError(f'Expected {value!r} to be a str')
if self.minsize is not None and len(value) < self.minsize:
raise ValueError(
f'Expected {value!r} to be no smaller than {self.minsize!r}'
)
if self.maxsize is not None and len(value) > self.maxsize:
raise ValueError(
f'Expected {value!r} to be no bigger than {self.maxsize!r}'
)
if self.predicate is not None and not self.predicate(value):
raise ValueError(
f'Expected {self.predicate} to be true for {value!r}'
)
Practical application¶
Here’s how the data validators can be used in a real class:
class Component:
name = String(minsize=3, maxsize=10, predicate=str.isupper)
kind = OneOf('wood', 'metal', 'plastic')
quantity = Number(minvalue=0)
def __init__(self, name, kind, quantity):
self.name = name
self.kind = kind
self.quantity = quantity
The descriptors prevent invalid instances from being created:
>>> Component('Widget', 'metal', 5) # Blocked: 'Widget' is not all uppercase
Traceback (most recent call last):
...
ValueError: Expected <method 'isupper' of 'str' objects> to be true for 'Widget'
>>> Component('WIDGET', 'metle', 5) # Blocked: 'metle' is misspelled
Traceback (most recent call last):
...
ValueError: Expected 'metle' to be one of {'metal', 'plastic', 'wood'}
>>> Component('WIDGET', 'metal', -5) # Blocked: -5 is negative
Traceback (most recent call last):
...
ValueError: Expected -5 to be at least 0
>>> Component('WIDGET', 'metal', 'V') # Blocked: 'V' isn't a number
Traceback (most recent call last):
...
TypeError: Expected 'V' to be an int or float
>>> c = Component('WIDGET', 'metal', 5) # Allowed: The inputs are valid
Technical Tutorial¶
What follows is a more technical tutorial for the mechanics and details of how descriptors work.
Abstract¶
Defines descriptors, summarizes the protocol, and shows how descriptors are called. Provides an example showing how object relational mappings work.
Learning about descriptors not only provides access to a larger toolset, it creates a deeper understanding of how Python works.
Definition and introduction¶
In general, a descriptor is an attribute value that has one of the methods in
the descriptor protocol. Those methods are __get__()
, __set__()
,
and __delete__()
. If any of those methods are defined for an
attribute, it is said to be a descriptor.
The default behavior for attribute access is to get, set, or delete the
attribute from an object’s dictionary. For instance, a.x
has a lookup chain
starting with a.__dict__['x']
, then type(a).__dict__['x']
, and
continuing through the method resolution order of type(a)
. If the
looked-up value is an object defining one of the descriptor methods, then Python
may override the default behavior and invoke the descriptor method instead.
Where this occurs in the precedence chain depends on which descriptor methods
were defined.
Descriptors are a powerful, general purpose protocol. They are the mechanism
behind properties, methods, static methods, class methods, and
super()
. They are used throughout Python itself. Descriptors
simplify the underlying C code and offer a flexible set of new tools for
everyday Python programs.
Descriptor protocol¶
descr.__get__(self, obj, type=None)
descr.__set__(self, obj, value)
descr.__delete__(self, obj)
That is all there is to it. Define any of these methods and an object is considered a descriptor and can override default behavior upon being looked up as an attribute.
If an object defines __set__()
or __delete__()
, it is considered
a data descriptor. Descriptors that only define __get__()
are called
non-data descriptors (they are often used for methods but other uses are
possible).
Data and non-data descriptors differ in how overrides are calculated with respect to entries in an instance’s dictionary. If an instance’s dictionary has an entry with the same name as a data descriptor, the data descriptor takes precedence. If an instance’s dictionary has an entry with the same name as a non-data descriptor, the dictionary entry takes precedence.
To make a read-only data descriptor, define both __get__()
and
__set__()
with the __set__()
raising an AttributeError
when
called. Defining the __set__()
method with an exception raising
placeholder is enough to make it a data descriptor.
Overview of descriptor invocation¶
A descriptor can be called directly with desc.__get__(obj)
or
desc.__get__(None, cls)
.
But it is more common for a descriptor to be invoked automatically from attribute access.
The expression obj.x
looks up the attribute x
in the chain of
namespaces for obj
. If the search finds a descriptor outside of the
instance __dict__
, its __get__()
method is
invoked according to the precedence rules listed below.
The details of invocation depend on whether obj
is an object, class, or
instance of super.
Invocation from an instance¶
Instance lookup scans through a chain of namespaces giving data descriptors
the highest priority, followed by instance variables, then non-data
descriptors, then class variables, and lastly __getattr__()
if it is
provided.
If a descriptor is found for a.x
, then it is invoked with:
desc.__get__(a, type(a))
.
The logic for a dotted lookup is in object.__getattribute__()
. Here is
a pure Python equivalent:
def find_name_in_mro(cls, name, default):
"Emulate _PyType_Lookup() in Objects/typeobject.c"
for base in cls.__mro__:
if name in vars(base):
return vars(base)[name]
return default
def object_getattribute(obj, name):
"Emulate PyObject_GenericGetAttr() in Objects/object.c"
null = object()
objtype = type(obj)
cls_var = find_name_in_mro(objtype, name, null)
descr_get = getattr(type(cls_var), '__get__', null)
if descr_get is not null:
if (hasattr(type(cls_var), '__set__')
or hasattr(type(cls_var), '__delete__')):
return descr_get(cls_var, obj, objtype) # data descriptor
if hasattr(obj, '__dict__') and name in vars(obj):
return vars(obj)[name] # instance variable
if descr_get is not null:
return descr_get(cls_var, obj, objtype) # non-data descriptor
if cls_var is not null:
return cls_var # class variable
raise AttributeError(name)
Note, there is no __getattr__()
hook in the __getattribute__()
code. That is why calling __getattribute__()
directly or with
super().__getattribute__
will bypass __getattr__()
entirely.
Instead, it is the dot operator and the getattr()
function that are
responsible for invoking __getattr__()
whenever __getattribute__()
raises an AttributeError
. Their logic is encapsulated in a helper
function:
def getattr_hook(obj, name):
"Emulate slot_tp_getattr_hook() in Objects/typeobject.c"
try:
return obj.__getattribute__(name)
except AttributeError:
if not hasattr(type(obj), '__getattr__'):
raise
return type(obj).__getattr__(obj, name) # __getattr__
Invocation from a class¶
The logic for a dotted lookup such as A.x
is in
type.__getattribute__()
. The steps are similar to those for
object.__getattribute__()
but the instance dictionary lookup is replaced
by a search through the class’s method resolution order.
If a descriptor is found, it is invoked with desc.__get__(None, A)
.
The full C implementation can be found in type_getattro()
and
_PyType_Lookup()
in Objects/typeobject.c.
Invocation from super¶
The logic for super’s dotted lookup is in the __getattribute__()
method for
object returned by super()
.
A dotted lookup such as super(A, obj).m
searches obj.__class__.__mro__
for the base class B
immediately following A
and then returns
B.__dict__['m'].__get__(obj, A)
. If not a descriptor, m
is returned
unchanged.
The full C implementation can be found in super_getattro()
in
Objects/typeobject.c. A pure Python equivalent can be found in
Guido’s Tutorial.
Summary of invocation logic¶
The mechanism for descriptors is embedded in the __getattribute__()
methods for object
, type
, and super()
.
The important points to remember are:
Descriptors are invoked by the
__getattribute__()
method.Classes inherit this machinery from
object
,type
, orsuper()
.Overriding
__getattribute__()
prevents automatic descriptor calls because all the descriptor logic is in that method.object.__getattribute__()
andtype.__getattribute__()
make different calls to__get__()
. The first includes the instance and may include the class. The second puts inNone
for the instance and always includes the class.Data descriptors always override instance dictionaries.
Non-data descriptors may be overridden by instance dictionaries.
Automatic name notification¶
Sometimes it is desirable for a descriptor to know what class variable name it
was assigned to. When a new class is created, the type
metaclass
scans the dictionary of the new class. If any of the entries are descriptors
and if they define __set_name__()
, that method is called with two
arguments. The owner is the class where the descriptor is used, and the
name is the class variable the descriptor was assigned to.
The implementation details are in type_new()
and
set_names()
in Objects/typeobject.c.
Since the update logic is in type.__new__()
, notifications only take
place at the time of class creation. If descriptors are added to the class
afterwards, __set_name__()
will need to be called manually.
ORM example¶
The following code is a simplified skeleton showing how data descriptors could be used to implement an object relational mapping.
The essential idea is that the data is stored in an external database. The Python instances only hold keys to the database’s tables. Descriptors take care of lookups or updates:
class Field:
def __set_name__(self, owner, name):
self.fetch = f'SELECT {name} FROM {owner.table} WHERE {owner.key}=?;'
self.store = f'UPDATE {owner.table} SET {name}=? WHERE {owner.key}=?;'
def __get__(self, obj, objtype=None):
return conn.execute(self.fetch, [obj.key]).fetchone()[0]
def __set__(self, obj, value):
conn.execute(self.store, [value, obj.key])
conn.commit()
We can use the Field
class to define models that describe the schema for
each table in a database:
class Movie:
table = 'Movies' # Table name
key = 'title' # Primary key
director = Field()
year = Field()
def __init__(self, key):
self.key = key
class Song:
table = 'Music'
key = 'title'
artist = Field()
year = Field()
genre = Field()
def __init__(self, key):
self.key = key
To use the models, first connect to the database:
>>> import sqlite3
>>> conn = sqlite3.connect('entertainment.db')
An interactive session shows how data is retrieved from the database and how it can be updated:
>>> Movie('Star Wars').director
'George Lucas'
>>> jaws = Movie('Jaws')
>>> f'Released in {jaws.year} by {jaws.director}'
'Released in 1975 by Steven Spielberg'
>>> Song('Country Roads').artist
'John Denver'
>>> Movie('Star Wars').director = 'J.J. Abrams'
>>> Movie('Star Wars').director
'J.J. Abrams'
Pure Python Equivalents¶
The descriptor protocol is simple and offers exciting possibilities. Several use cases are so common that they have been prepackaged into built-in tools. Properties, bound methods, static methods, class methods, and __slots__ are all based on the descriptor protocol.
Properties¶
Calling property()
is a succinct way of building a data descriptor that
triggers a function call upon access to an attribute. Its signature is:
property(fget=None, fset=None, fdel=None, doc=None) -> property
The documentation shows a typical use to define a managed attribute x
:
class C:
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")
To see how property()
is implemented in terms of the descriptor protocol,
here is a pure Python equivalent that implements most of the core functionality:
class Property:
"Emulate PyProperty_Type() in Objects/descrobject.c"
def __init__(self, fget=None, fset=None, fdel=None, doc=None):
self.fget = fget
self.fset = fset
self.fdel = fdel
if doc is None and fget is not None:
doc = fget.__doc__
self.__doc__ = doc
def __set_name__(self, owner, name):
self.__name__ = name
def __get__(self, obj, objtype=None):
if obj is None:
return self
if self.fget is None:
raise AttributeError
return self.fget(obj)
def __set__(self, obj, value):
if self.fset is None:
raise AttributeError
self.fset(obj, value)
def __delete__(self, obj):
if self.fdel is None:
raise AttributeError
self.fdel(obj)
def getter(self, fget):
return type(self)(fget, self.fset, self.fdel, self.__doc__)
def setter(self, fset):
return type(self)(self.fget, fset, self.fdel, self.__doc__)
def deleter(self, fdel):
return type(self)(self.fget, self.fset, fdel, self.__doc__)
The property()
builtin helps whenever a user interface has granted
attribute access and then subsequent changes require the intervention of a
method.
For instance, a spreadsheet class may grant access to a cell value through
Cell('b10').value
. Subsequent improvements to the program require the cell
to be recalculated on every access; however, the programmer does not want to
affect existing client code accessing the attribute directly. The solution is
to wrap access to the value attribute in a property data descriptor:
class Cell:
...
@property
def value(self):
"Recalculate the cell before returning value"
self.recalc()
return self._value
Either the built-in property()
or our Property()
equivalent would
work in this example.
Functions and methods¶
Python’s object oriented features are built upon a function based environment. Using non-data descriptors, the two are merged seamlessly.
Functions stored in class dictionaries get turned into methods when invoked. Methods only differ from regular functions in that the object instance is prepended to the other arguments. By convention, the instance is called self but could be called this or any other variable name.
Methods can be created manually with types.MethodType
which is
roughly equivalent to:
class MethodType:
"Emulate PyMethod_Type in Objects/classobject.c"
def __init__(self, func, obj):
self.__func__ = func
self.__self__ = obj
def __call__(self, *args, **kwargs):
func = self.__func__
obj = self.__self__
return func(obj, *args, **kwargs)
def __getattribute__(self, name):
"Emulate method_getset() in Objects/classobject.c"
if name == '__doc__':
return self.__func__.__doc__
return object.__getattribute__(self, name)
def __getattr__(self, name):
"Emulate method_getattro() in Objects/classobject.c"
return getattr(self.__func__, name)
def __get__(self, obj, objtype=None):
"Emulate method_descr_get() in Objects/classobject.c"
return self
To support automatic creation of methods, functions include the
__get__()
method for binding methods during attribute access. This
means that functions are non-data descriptors that return bound methods
during dotted lookup from an instance. Here’s how it works:
class Function:
...
def __get__(self, obj, objtype=None):
"Simulate func_descr_get() in Objects/funcobject.c"
if obj is None:
return self
return MethodType(self, obj)
Running the following class in the interpreter shows how the function descriptor works in practice:
class D:
def f(self):
return self
class D2:
pass
The function has a qualified name attribute to support introspection:
>>> D.f.__qualname__
'D.f'
Accessing the function through the class dictionary does not invoke
__get__()
. Instead, it just returns the underlying function object:
>>> D.__dict__['f']
<function D.f at 0x00C45070>
Dotted access from a class calls __get__()
which just returns the
underlying function unchanged:
>>> D.f
<function D.f at 0x00C45070>
The interesting behavior occurs during dotted access from an instance. The
dotted lookup calls __get__()
which returns a bound method object:
>>> d = D()
>>> d.f
<bound method D.f of <__main__.D object at 0x00B18C90>>
Internally, the bound method stores the underlying function and the bound instance:
>>> d.f.__func__
<function D.f at 0x00C45070>
>>> d.f.__self__
<__main__.D object at 0x00B18C90>
If you have ever wondered where self comes from in regular methods or where cls comes from in class methods, this is it!
Kinds of methods¶
Non-data descriptors provide a simple mechanism for variations on the usual patterns of binding functions into methods.
To recap, functions have a __get__()
method so that they can be converted
to a method when accessed as attributes. The non-data descriptor transforms an
obj.f(*args)
call into f(obj, *args)
. Calling cls.f(*args)
becomes f(*args)
.
This chart summarizes the binding and its two most useful variants:
Transformation
Called from an object
Called from a class
function
f(obj, *args)
f(*args)
staticmethod
f(*args)
f(*args)
classmethod
f(type(obj), *args)
f(cls, *args)
Static methods¶
Static methods return the underlying function without changes. Calling either
c.f
or C.f
is the equivalent of a direct lookup into
object.__getattribute__(c, "f")
or object.__getattribute__(C, "f")
. As a
result, the function becomes identically accessible from either an object or a
class.
Good candidates for static methods are methods that do not reference the
self
variable.
For instance, a statistics package may include a container class for
experimental data. The class provides normal methods for computing the average,
mean, median, and other descriptive statistics that depend on the data. However,
there may be useful functions which are conceptually related but do not depend
on the data. For instance, erf(x)
is handy conversion routine that comes up
in statistical work but does not directly depend on a particular dataset.
It can be called either from an object or the class: s.erf(1.5) --> 0.9332
or Sample.erf(1.5) --> 0.9332
.
Since static methods return the underlying function with no changes, the example calls are unexciting:
class E:
@staticmethod
def f(x):
return x * 10
>>> E.f(3)
30
>>> E().f(3)
30
Using the non-data descriptor protocol, a pure Python version of
staticmethod()
would look like this:
import functools
class StaticMethod:
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
functools.update_wrapper(self, f)
def __get__(self, obj, objtype=None):
return self.f
def __call__(self, *args, **kwds):
return self.f(*args, **kwds)
@property
def __annotations__(self):
return self.f.__annotations__
The functools.update_wrapper()
call adds a __wrapped__
attribute
that refers to the underlying function. Also it carries forward
the attributes necessary to make the wrapper look like the wrapped
function, including __name__
, __qualname__
,
and __doc__
.
Class methods¶
Unlike static methods, class methods prepend the class reference to the argument list before calling the function. This format is the same for whether the caller is an object or a class:
class F:
@classmethod
def f(cls, x):
return cls.__name__, x
>>> F.f(3)
('F', 3)
>>> F().f(3)
('F', 3)
This behavior is useful whenever the method only needs to have a class
reference and does not rely on data stored in a specific instance. One use for
class methods is to create alternate class constructors. For example, the
classmethod dict.fromkeys()
creates a new dictionary from a list of
keys. The pure Python equivalent is:
class Dict(dict):
@classmethod
def fromkeys(cls, iterable, value=None):
"Emulate dict_fromkeys() in Objects/dictobject.c"
d = cls()
for key in iterable:
d[key] = value
return d
Now a new dictionary of unique keys can be constructed like this:
>>> d = Dict.fromkeys('abracadabra')
>>> type(d) is Dict
True
>>> d
{'a': None, 'b': None, 'r': None, 'c': None, 'd': None}
Using the non-data descriptor protocol, a pure Python version of
classmethod()
would look like this:
import functools
class ClassMethod:
"Emulate PyClassMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
functools.update_wrapper(self, f)
def __get__(self, obj, cls=None):
if cls is None:
cls = type(obj)
return MethodType(self.f, cls)
The functools.update_wrapper()
call in ClassMethod
adds a
__wrapped__
attribute that refers to the underlying function. Also
it carries forward the attributes necessary to make the wrapper look
like the wrapped function: __name__
,
__qualname__
, __doc__
,
and __annotations__
.
Member objects and __slots__¶
When a class defines __slots__
, it replaces instance dictionaries with a
fixed-length array of slot values. From a user point of view that has
several effects:
1. Provides immediate detection of bugs due to misspelled attribute
assignments. Only attribute names specified in __slots__
are allowed:
class Vehicle:
__slots__ = ('id_number', 'make', 'model')
>>> auto = Vehicle()
>>> auto.id_nubmer = 'VYE483814LQEX'
Traceback (most recent call last):
...
AttributeError: 'Vehicle' object has no attribute 'id_nubmer'
2. Helps create immutable objects where descriptors manage access to private
attributes stored in __slots__
:
class Immutable:
__slots__ = ('_dept', '_name') # Replace the instance dictionary
def __init__(self, dept, name):
self._dept = dept # Store to private attribute
self._name = name # Store to private attribute
@property # Read-only descriptor
def dept(self):
return self._dept
@property
def name(self): # Read-only descriptor
return self._name
>>> mark = Immutable('Botany', 'Mark Watney')
>>> mark.dept
'Botany'
>>> mark.dept = 'Space Pirate'
Traceback (most recent call last):
...
AttributeError: property 'dept' of 'Immutable' object has no setter
>>> mark.location = 'Mars'
Traceback (most recent call last):
...
AttributeError: 'Immutable' object has no attribute 'location'
3. Saves memory. On a 64-bit Linux build, an instance with two attributes
takes 48 bytes with __slots__
and 152 bytes without. This flyweight
design pattern likely only
matters when a large number of instances are going to be created.
4. Improves speed. Reading instance variables is 35% faster with
__slots__
(as measured with Python 3.10 on an Apple M1 processor).
5. Blocks tools like functools.cached_property()
which require an
instance dictionary to function correctly:
from functools import cached_property
class CP:
__slots__ = () # Eliminates the instance dict
@cached_property # Requires an instance dict
def pi(self):
return 4 * sum((-1.0)**n / (2.0*n + 1.0)
for n in reversed(range(100_000)))
>>> CP().pi
Traceback (most recent call last):
...
TypeError: No '__dict__' attribute on 'CP' instance to cache 'pi' property.
It is not possible to create an exact drop-in pure Python version of
__slots__
because it requires direct access to C structures and control
over object memory allocation. However, we can build a mostly faithful
simulation where the actual C structure for slots is emulated by a private
_slotvalues
list. Reads and writes to that private structure are managed
by member descriptors:
null = object()
class Member:
def __init__(self, name, clsname, offset):
'Emulate PyMemberDef in Include/structmember.h'
# Also see descr_new() in Objects/descrobject.c
self.name = name
self.clsname = clsname
self.offset = offset
def __get__(self, obj, objtype=None):
'Emulate member_get() in Objects/descrobject.c'
# Also see PyMember_GetOne() in Python/structmember.c
if obj is None:
return self
value = obj._slotvalues[self.offset]
if value is null:
raise AttributeError(self.name)
return value
def __set__(self, obj, value):
'Emulate member_set() in Objects/descrobject.c'
obj._slotvalues[self.offset] = value
def __delete__(self, obj):
'Emulate member_delete() in Objects/descrobject.c'
value = obj._slotvalues[self.offset]
if value is null:
raise AttributeError(self.name)
obj._slotvalues[self.offset] = null
def __repr__(self):
'Emulate member_repr() in Objects/descrobject.c'
return f'<Member {self.name!r} of {self.clsname!r}>'
The type.__new__()
method takes care of adding member objects to class
variables:
class Type(type):
'Simulate how the type metaclass adds member objects for slots'
def __new__(mcls, clsname, bases, mapping, **kwargs):
'Emulate type_new() in Objects/typeobject.c'
# type_new() calls PyTypeReady() which calls add_methods()
slot_names = mapping.get('slot_names', [])
for offset, name in enumerate(slot_names):
mapping[name] = Member(name, clsname, offset)
return type.__new__(mcls, clsname, bases, mapping, **kwargs)
The object.__new__()
method takes care of creating instances that have
slots instead of an instance dictionary. Here is a rough simulation in pure
Python:
class Object:
'Simulate how object.__new__() allocates memory for __slots__'
def __new__(cls, *args, **kwargs):
'Emulate object_new() in Objects/typeobject.c'
inst = super().__new__(cls)
if hasattr(cls, 'slot_names'):
empty_slots = [null] * len(cls.slot_names)
object.__setattr__(inst, '_slotvalues', empty_slots)
return inst
def __setattr__(self, name, value):
'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'
cls = type(self)
if hasattr(cls, 'slot_names') and name not in cls.slot_names:
raise AttributeError(
f'{cls.__name__!r} object has no attribute {name!r}'
)
super().__setattr__(name, value)
def __delattr__(self, name):
'Emulate _PyObject_GenericSetAttrWithDict() Objects/object.c'
cls = type(self)
if hasattr(cls, 'slot_names') and name not in cls.slot_names:
raise AttributeError(
f'{cls.__name__!r} object has no attribute {name!r}'
)
super().__delattr__(name)
To use the simulation in a real class, just inherit from Object
and
set the metaclass to Type
:
class H(Object, metaclass=Type):
'Instance variables stored in slots'
slot_names = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
At this point, the metaclass has loaded member objects for x and y:
>>> from pprint import pp
>>> pp(dict(vars(H)))
{'__module__': '__main__',
'__doc__': 'Instance variables stored in slots',
'slot_names': ['x', 'y'],
'__init__': <function H.__init__ at 0x7fb5d302f9d0>,
'x': <Member 'x' of 'H'>,
'y': <Member 'y' of 'H'>}
When instances are created, they have a slot_values
list where the
attributes are stored:
>>> h = H(10, 20)
>>> vars(h)
{'_slotvalues': [10, 20]}
>>> h.x = 55
>>> vars(h)
{'_slotvalues': [55, 20]}
Misspelled or unassigned attributes will raise an exception:
>>> h.xz
Traceback (most recent call last):
...
AttributeError: 'H' object has no attribute 'xz'