Python code modernization, 3/n (#1157)

* Remove __metaclass__ = type.

for i in $(grep -REl '__metaclass__ = type' plugins/ tests/); do
  sed -e '/^__metaclass__ = type/d' -i $i;
done

* Remove super arguments, and stop inheriting from object.
This commit is contained in:
Felix Fontein
2025-10-10 08:11:58 +02:00
committed by GitHub
parent 741c318b1d
commit e8ec22d3b1
99 changed files with 129 additions and 245 deletions
+6 -6
View File
@@ -30,10 +30,10 @@ try:
except ImportError:
REQUESTS_IMPORT_ERROR = traceback.format_exc()
class Session(object):
class Session:
__attrs__ = []
class HTTPAdapter(object):
class HTTPAdapter:
__attrs__ = []
class HTTPError(Exception):
@@ -57,13 +57,13 @@ except ImportError:
except ImportError:
URLLIB3_IMPORT_ERROR = traceback.format_exc()
class _HTTPConnectionPool(object):
class _HTTPConnectionPool:
pass
class _HTTPConnection(object):
class _HTTPConnection:
pass
class FakeURLLIB3(object):
class FakeURLLIB3:
def __init__(self):
self._collections = self
self.poolmanager = self
@@ -75,7 +75,7 @@ except ImportError:
self.match_hostname = object()
self.HTTPConnectionPool = _HTTPConnectionPool
class FakeURLLIB3Connection(object):
class FakeURLLIB3Connection:
def __init__(self):
self.HTTPConnection = _HTTPConnection
+2 -2
View File
@@ -115,7 +115,7 @@ class APIClient(_Session, DaemonApiMixin):
use_ssh_client=False,
max_pool_size=DEFAULT_MAX_POOL_SIZE,
):
super(APIClient, self).__init__()
super().__init__()
fail_on_missing_imports()
@@ -493,7 +493,7 @@ class APIClient(_Session, DaemonApiMixin):
def get_adapter(self, url):
try:
return super(APIClient, self).get_adapter(url)
return super().get_adapter(url)
except _InvalidSchema as e:
if self._custom_adapter:
return self._custom_adapter
+1 -1
View File
@@ -17,7 +17,7 @@ from .. import auth
from ..utils.decorators import minimum_version
class DaemonApiMixin(object):
class DaemonApiMixin:
@minimum_version("1.25")
def df(self):
"""
+1 -1
View File
@@ -33,7 +33,7 @@ def create_default_context():
)
class ContextAPI(object):
class ContextAPI:
"""Context API.
Contains methods for context management:
create, list, remove, get, inspect.
+1 -1
View File
@@ -28,7 +28,7 @@ from .config import (
IN_MEMORY = "IN MEMORY"
class Context(object):
class Context:
"""A context."""
def __init__(
@@ -19,7 +19,7 @@ from . import constants, errors
from .utils import create_environment_dict, find_executable
class Store(object):
class Store:
def __init__(self, program, environment=None):
"""Create a store object that acts as an interface to
perform the basic operations for storing, retrieving
+4 -4
View File
@@ -55,12 +55,12 @@ class APIError(_HTTPError, DockerException):
def __init__(self, message, response=None, explanation=None):
# requests 1.2 supports response as a keyword argument, but
# requests 1.1 does not
super(APIError, self).__init__(message)
super().__init__(message)
self.response = response
self.explanation = explanation
def __str__(self):
message = super(APIError, self).__str__()
message = super().__str__()
if self.is_client_error():
message = f"{self.response.status_code} Client Error for {self.response.url}: {self.response.reason}"
@@ -152,7 +152,7 @@ class ContainerError(DockerException):
err = f": {stderr}" if stderr is not None else ""
msg = f"Command '{command}' in image '{image}' returned non-zero exit status {exit_status}{err}"
super(ContainerError, self).__init__(msg)
super().__init__(msg)
class StreamParseError(RuntimeError):
@@ -162,7 +162,7 @@ class StreamParseError(RuntimeError):
class BuildError(DockerException):
def __init__(self, reason, build_log):
super(BuildError, self).__init__(reason)
super().__init__(reason)
self.msg = reason
self.build_log = build_log
+1 -1
View File
@@ -18,7 +18,7 @@ from . import errors
from .transport.ssladapter import SSLHTTPAdapter
class TLSConfig(object):
class TLSConfig:
"""
TLS configuration.
@@ -16,7 +16,7 @@ from .._import_helper import HTTPAdapter as _HTTPAdapter
class BaseHTTPAdapter(_HTTPAdapter):
def close(self):
super(BaseHTTPAdapter, self).close()
super().close()
if hasattr(self, "pools"):
self.pools.clear()
@@ -22,9 +22,9 @@ from .npipesocket import NpipeSocket
RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer
class NpipeHTTPConnection(urllib3_connection.HTTPConnection, object):
class NpipeHTTPConnection(urllib3_connection.HTTPConnection):
def __init__(self, npipe_path, timeout=60):
super(NpipeHTTPConnection, self).__init__("localhost", timeout=timeout)
super().__init__("localhost", timeout=timeout)
self.npipe_path = npipe_path
self.timeout = timeout
@@ -37,9 +37,7 @@ class NpipeHTTPConnection(urllib3_connection.HTTPConnection, object):
class NpipeHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
def __init__(self, npipe_path, timeout=60, maxsize=10):
super(NpipeHTTPConnectionPool, self).__init__(
"localhost", timeout=timeout, maxsize=maxsize
)
super().__init__("localhost", timeout=timeout, maxsize=maxsize)
self.npipe_path = npipe_path
self.timeout = timeout
@@ -90,7 +88,7 @@ class NpipeHTTPAdapter(BaseHTTPAdapter):
self.pools = RecentlyUsedContainer(
pool_connections, dispose_func=lambda p: p.close()
)
super(NpipeHTTPAdapter, self).__init__()
super().__init__()
def get_connection(self, url, proxies=None):
with self.pools.lock:
@@ -45,7 +45,7 @@ def check_closed(f):
return wrapped
class NpipeSocket(object):
class NpipeSocket:
"""Partial implementation of the socket API over windows named pipes.
This implementation is only designed to be used as a client socket,
and server-specific methods (bind, listen, accept...) are not
@@ -227,7 +227,7 @@ class NpipeFileIOBase(io.RawIOBase):
self.sock = npipe_socket
def close(self):
super(NpipeFileIOBase, self).close()
super().close()
self.sock = None
def fileno(self):
@@ -37,7 +37,7 @@ RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer
class SSHSocket(socket.socket):
def __init__(self, host):
super(SSHSocket, self).__init__(socket.AF_INET, socket.SOCK_STREAM)
super().__init__(socket.AF_INET, socket.SOCK_STREAM)
self.host = host
self.port = None
self.user = None
@@ -117,9 +117,9 @@ class SSHSocket(socket.socket):
self.proc.terminate()
class SSHConnection(urllib3_connection.HTTPConnection, object):
class SSHConnection(urllib3_connection.HTTPConnection):
def __init__(self, ssh_transport=None, timeout=60, host=None):
super(SSHConnection, self).__init__("localhost", timeout=timeout)
super().__init__("localhost", timeout=timeout)
self.ssh_transport = ssh_transport
self.timeout = timeout
self.ssh_host = host
@@ -141,9 +141,7 @@ class SSHConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
scheme = "ssh"
def __init__(self, ssh_client=None, timeout=60, maxsize=10, host=None):
super(SSHConnectionPool, self).__init__(
"localhost", timeout=timeout, maxsize=maxsize
)
super().__init__("localhost", timeout=timeout, maxsize=maxsize)
self.ssh_transport = None
self.timeout = timeout
if ssh_client:
@@ -207,7 +205,7 @@ class SSHHTTPAdapter(BaseHTTPAdapter):
self.pools = RecentlyUsedContainer(
pool_connections, dispose_func=lambda p: p.close()
)
super(SSHHTTPAdapter, self).__init__()
super().__init__()
def _create_paramiko_client(self, base_url):
logging.getLogger("paramiko").setLevel(logging.WARNING)
@@ -272,6 +270,6 @@ class SSHHTTPAdapter(BaseHTTPAdapter):
return pool
def close(self):
super(SSHHTTPAdapter, self).close()
super().close()
if self.ssh_client:
self.ssh_client.close()
@@ -35,7 +35,7 @@ class SSLHTTPAdapter(BaseHTTPAdapter):
def __init__(self, ssl_version=None, assert_hostname=None, **kwargs):
self.ssl_version = ssl_version
self.assert_hostname = assert_hostname
super(SSLHTTPAdapter, self).__init__(**kwargs)
super().__init__(**kwargs)
def init_poolmanager(self, connections, maxsize, block=False):
kwargs = {
@@ -58,7 +58,7 @@ class SSLHTTPAdapter(BaseHTTPAdapter):
But we still need to take care of when there is a proxy poolmanager
"""
conn = super(SSLHTTPAdapter, self).get_connection(*args, **kwargs)
conn = super().get_connection(*args, **kwargs)
if (
self.assert_hostname is not None
and conn.assert_hostname != self.assert_hostname
@@ -21,10 +21,10 @@ from .basehttpadapter import BaseHTTPAdapter
RecentlyUsedContainer = urllib3._collections.RecentlyUsedContainer
class UnixHTTPConnection(urllib3_connection.HTTPConnection, object):
class UnixHTTPConnection(urllib3_connection.HTTPConnection):
def __init__(self, base_url, unix_socket, timeout=60):
super(UnixHTTPConnection, self).__init__("localhost", timeout=timeout)
super().__init__("localhost", timeout=timeout)
self.base_url = base_url
self.unix_socket = unix_socket
self.timeout = timeout
@@ -37,7 +37,7 @@ class UnixHTTPConnection(urllib3_connection.HTTPConnection, object):
self.sock = sock
def putheader(self, header, *values):
super(UnixHTTPConnection, self).putheader(header, *values)
super().putheader(header, *values)
if header == "Connection" and "Upgrade" in values:
self.disable_buffering = True
@@ -45,14 +45,12 @@ class UnixHTTPConnection(urllib3_connection.HTTPConnection, object):
# FIXME: We may need to disable buffering on Py3,
# but there's no clear way to do it at the moment. See:
# https://github.com/docker/docker-py/issues/1799
return super(UnixHTTPConnection, self).response_class(sock, *args, **kwargs)
return super().response_class(sock, *args, **kwargs)
class UnixHTTPConnectionPool(urllib3.connectionpool.HTTPConnectionPool):
def __init__(self, base_url, socket_path, timeout=60, maxsize=10):
super(UnixHTTPConnectionPool, self).__init__(
"localhost", timeout=timeout, maxsize=maxsize
)
super().__init__("localhost", timeout=timeout, maxsize=maxsize)
self.base_url = base_url
self.socket_path = socket_path
self.timeout = timeout
@@ -86,7 +84,7 @@ class UnixHTTPAdapter(BaseHTTPAdapter):
self.pools = RecentlyUsedContainer(
pool_connections, dispose_func=lambda p: p.close()
)
super(UnixHTTPAdapter, self).__init__()
super().__init__()
def get_connection(self, url, proxies=None):
with self.pools.lock:
+1 -1
View File
@@ -17,7 +17,7 @@ from .._import_helper import urllib3
from ..errors import DockerException
class CancellableStream(object):
class CancellableStream:
"""
Stream wrapper for real-time events, logs, etc. from the server.
+2 -2
View File
@@ -158,7 +158,7 @@ def walk(root, patterns, default=True):
# Heavily based on
# https://github.com/moby/moby/blob/master/pkg/fileutils/fileutils.go
class PatternMatcher(object):
class PatternMatcher:
def __init__(self, patterns):
self.patterns = list(filter(lambda p: p.dirs, [Pattern(p) for p in patterns]))
self.patterns.append(Pattern("!.dockerignore"))
@@ -216,7 +216,7 @@ class PatternMatcher(object):
return rec_walk(root)
class Pattern(object):
class Pattern:
def __init__(self, pattern_str):
self.exclusion = False
if pattern_str.startswith("!"):
+4 -6
View File
@@ -101,7 +101,7 @@ if not HAS_DOCKER_PY:
# No Docker SDK for Python. Create a place holder client to allow
# instantiation of AnsibleModule and proper error handing
class Client(object): # noqa: F811, pylint: disable=function-redefined
class Client: # noqa: F811, pylint: disable=function-redefined
def __init__(self, **kwargs):
pass
@@ -232,7 +232,7 @@ class AnsibleDockerClientBase(Client):
)
try:
super(AnsibleDockerClientBase, self).__init__(**self._connect_params)
super().__init__(**self._connect_params)
self.docker_api_version_str = self.api_version
except APIError as exc:
self.fail(f"Docker API error: {exc}")
@@ -628,9 +628,7 @@ class AnsibleDockerClientBase(Client):
),
get_json=True,
)
return super(AnsibleDockerClientBase, self).inspect_distribution(
image, **kwargs
)
return super().inspect_distribution(image, **kwargs)
class AnsibleDockerClient(AnsibleDockerClientBase):
@@ -684,7 +682,7 @@ class AnsibleDockerClient(AnsibleDockerClientBase):
self.debug = self.module.params.get("debug")
self.check_mode = self.module.check_mode
super(AnsibleDockerClient, self).__init__(
super().__init__(
min_docker_version=min_docker_version,
min_docker_api_version=min_docker_api_version,
)
+2 -4
View File
@@ -119,7 +119,7 @@ class AnsibleDockerClientBase(Client):
)
try:
super(AnsibleDockerClientBase, self).__init__(**self._connect_params)
super().__init__(**self._connect_params)
self.docker_api_version_str = self.api_version
except MissingRequirementException as exc:
self.fail(
@@ -592,9 +592,7 @@ class AnsibleDockerClient(AnsibleDockerClientBase):
self.debug = self.module.params.get("debug")
self.check_mode = self.module.check_mode
super(AnsibleDockerClient, self).__init__(
min_docker_api_version=min_docker_api_version
)
super().__init__(min_docker_api_version=min_docker_api_version)
if option_minimal_versions is not None:
self._get_minimal_versions(
+2 -2
View File
@@ -61,7 +61,7 @@ class DockerException(Exception):
pass
class AnsibleDockerClientBase(object):
class AnsibleDockerClientBase:
def __init__(
self, common_args, min_docker_api_version=None, needs_api_version=True
):
@@ -357,7 +357,7 @@ class AnsibleModuleDockerClient(AnsibleDockerClientBase):
self.diff = self.module._diff
common_args = dict((k, self.module.params[k]) for k in DOCKER_COMMON_ARGS)
super(AnsibleModuleDockerClient, self).__init__(
super().__init__(
common_args,
min_docker_api_version=min_docker_api_version,
needs_api_version=needs_api_version,
+2 -2
View File
@@ -132,7 +132,7 @@ DOCKER_PULL_PROGRESS_WORKING = frozenset(
)
class ResourceType(object):
class ResourceType:
UNKNOWN = "unknown"
NETWORK = "network"
IMAGE = "image"
@@ -724,7 +724,7 @@ def combine_text_output(*outputs):
class BaseComposeManager(DockerBaseClass):
def __init__(self, client, min_version=MINIMUM_COMPOSE_VERSION):
super(BaseComposeManager, self).__init__()
super().__init__()
self.client = client
self.check_mode = self.client.check_mode
self.cleanup_dirs = set()
+1 -1
View File
@@ -12,7 +12,7 @@ import os
import tarfile
class ImageArchiveManifestSummary(object):
class ImageArchiveManifestSummary:
"""
Represents data extracted from a manifest.json found in the tar archive output of the
"docker image save some:tag > some.tar" command.
+2 -2
View File
@@ -22,7 +22,7 @@ class InvalidLogFmt(Exception):
pass
class _Mode(object):
class _Mode:
GARBAGE = 0
KEY = 1
EQUAL = 2
@@ -72,7 +72,7 @@ def _is_ident(cur):
return cur > " " and cur not in ('"', "=")
class _Parser(object):
class _Parser:
def __init__(self, line):
self.line = line
self.index = 0
@@ -61,7 +61,7 @@ def _get_ansible_type(value_type):
return value_type
class Option(object):
class Option:
def __init__(
self,
name,
@@ -148,7 +148,7 @@ class Option(object):
)
class OptionGroup(object):
class OptionGroup:
def __init__(
self,
preprocess=None,
@@ -205,7 +205,7 @@ class OptionGroup(object):
return self
class Engine(object):
class Engine:
min_api_version = None # string or None
min_api_version_obj = None # LooseVersion object or None
extra_option_minimal_versions = None # dict[str, dict[str, Any]] or None
@@ -265,7 +265,7 @@ class Engine(object):
pass
class EngineDriver(object):
class EngineDriver:
name = None # string
@abc.abstractmethod
@@ -26,7 +26,7 @@ from ansible_collections.community.docker.plugins.module_utils._util import (
class Container(DockerBaseClass):
def __init__(self, container, engine_driver):
super(Container, self).__init__()
super().__init__()
self.raw = container
self.id = None
self.image = None
+1 -1
View File
@@ -128,7 +128,7 @@ def _normalize_arch(arch_str, variant_str):
return arch_str, variant_str
class _Platform(object):
class _Platform:
def __init__(self, os=None, arch=None, variant=None):
self.os = os
self.arch = arch
+2 -2
View File
@@ -25,7 +25,7 @@ from ansible_collections.community.docker.plugins.module_utils._socket_helper im
PARAMIKO_POLL_TIMEOUT = 0.01 # 10 milliseconds
class DockerSocketHandlerBase(object):
class DockerSocketHandlerBase:
def __init__(self, sock, selectors, log=None):
make_unblocking(sock)
@@ -212,4 +212,4 @@ class DockerSocketHandlerBase(object):
class DockerSocketHandlerModule(DockerSocketHandlerBase):
def __init__(self, sock, module, selectors):
super(DockerSocketHandlerModule, self).__init__(sock, selectors, module.debug)
super().__init__(sock, selectors, module.debug)
+2 -2
View File
@@ -29,7 +29,7 @@ from ansible_collections.community.docker.plugins.module_utils._version import (
class AnsibleDockerSwarmClient(AnsibleDockerClient):
def __init__(self, **kwargs):
super(AnsibleDockerSwarmClient, self).__init__(**kwargs)
super().__init__(**kwargs)
def get_swarm_node_id(self):
"""
@@ -271,7 +271,7 @@ class AnsibleDockerSwarmClient(AnsibleDockerClient):
def get_unlock_key(self):
if self.docker_py_version < LooseVersion("2.7.0"):
return None
return super(AnsibleDockerSwarmClient, self).get_unlock_key()
return super().get_unlock_key()
def get_service_inspect(self, service_id, skip_missing=False):
"""
+2 -2
View File
@@ -121,7 +121,7 @@ def log_debug(msg, pretty_print=False):
log_file.write(f"{msg}\n")
class DockerBaseClass(object):
class DockerBaseClass:
def __init__(self):
self.debug = False
@@ -245,7 +245,7 @@ def compare_generic(a, b, method, datatype):
return True
class DifferenceTracker(object):
class DifferenceTracker:
def __init__(self):
self._diff = []