Skip to content

Commit 5fcc293

Browse files
committed
use python3.6+ constructs
Signed-off-by: Anthony Sottile <[email protected]>
1 parent 650aad3 commit 5fcc293

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

92 files changed

+524
-658
lines changed

docker/api/build.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
log = logging.getLogger(__name__)
1313

1414

15-
class BuildApiMixin(object):
15+
class BuildApiMixin:
1616
def build(self, path=None, tag=None, quiet=False, fileobj=None,
1717
nocache=False, rm=False, timeout=None,
1818
custom_context=False, encoding=None, pull=False,
@@ -132,7 +132,7 @@ def build(self, path=None, tag=None, quiet=False, fileobj=None,
132132
for key in container_limits.keys():
133133
if key not in constants.CONTAINER_LIMITS_KEYS:
134134
raise errors.DockerException(
135-
'Invalid container_limits key {0}'.format(key)
135+
f'Invalid container_limits key {key}'
136136
)
137137

138138
if custom_context:
@@ -150,7 +150,7 @@ def build(self, path=None, tag=None, quiet=False, fileobj=None,
150150
dockerignore = os.path.join(path, '.dockerignore')
151151
exclude = None
152152
if os.path.exists(dockerignore):
153-
with open(dockerignore, 'r') as f:
153+
with open(dockerignore) as f:
154154
exclude = list(filter(
155155
lambda x: x != '' and x[0] != '#',
156156
[l.strip() for l in f.read().splitlines()]
@@ -313,7 +313,7 @@ def _set_auth_headers(self, headers):
313313
auth_data[auth.INDEX_URL] = auth_data.get(auth.INDEX_NAME, {})
314314

315315
log.debug(
316-
'Sending auth config ({0})'.format(
316+
'Sending auth config ({})'.format(
317317
', '.join(repr(k) for k in auth_data.keys())
318318
)
319319
)
@@ -344,9 +344,9 @@ def process_dockerfile(dockerfile, path):
344344
if (os.path.splitdrive(path)[0] != os.path.splitdrive(abs_dockerfile)[0] or
345345
os.path.relpath(abs_dockerfile, path).startswith('..')):
346346
# Dockerfile not in context - read data to insert into tar later
347-
with open(abs_dockerfile, 'r') as df:
347+
with open(abs_dockerfile) as df:
348348
return (
349-
'.dockerfile.{0:x}'.format(random.getrandbits(160)),
349+
f'.dockerfile.{random.getrandbits(160):x}',
350350
df.read()
351351
)
352352

docker/api/client.py

+9-11
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def __init__(self, base_url=None, version=None,
107107
user_agent=DEFAULT_USER_AGENT, num_pools=None,
108108
credstore_env=None, use_ssh_client=False,
109109
max_pool_size=DEFAULT_MAX_POOL_SIZE):
110-
super(APIClient, self).__init__()
110+
super().__init__()
111111

112112
if tls and not base_url:
113113
raise TLSParameterError(
@@ -199,7 +199,7 @@ def __init__(self, base_url=None, version=None,
199199
self._version = version
200200
if not isinstance(self._version, str):
201201
raise DockerException(
202-
'Version parameter must be a string or None. Found {0}'.format(
202+
'Version parameter must be a string or None. Found {}'.format(
203203
type(version).__name__
204204
)
205205
)
@@ -219,7 +219,7 @@ def _retrieve_server_version(self):
219219
)
220220
except Exception as e:
221221
raise DockerException(
222-
'Error while fetching server API version: {0}'.format(e)
222+
f'Error while fetching server API version: {e}'
223223
)
224224

225225
def _set_request_timeout(self, kwargs):
@@ -248,19 +248,19 @@ def _url(self, pathfmt, *args, **kwargs):
248248
for arg in args:
249249
if not isinstance(arg, str):
250250
raise ValueError(
251-
'Expected a string but found {0} ({1}) '
251+
'Expected a string but found {} ({}) '
252252
'instead'.format(arg, type(arg))
253253
)
254254

255255
quote_f = partial(urllib.parse.quote, safe="/:")
256256
args = map(quote_f, args)
257257

258258
if kwargs.get('versioned_api', True):
259-
return '{0}/v{1}{2}'.format(
259+
return '{}/v{}{}'.format(
260260
self.base_url, self._version, pathfmt.format(*args)
261261
)
262262
else:
263-
return '{0}{1}'.format(self.base_url, pathfmt.format(*args))
263+
return f'{self.base_url}{pathfmt.format(*args)}'
264264

265265
def _raise_for_status(self, response):
266266
"""Raises stored :class:`APIError`, if one occurred."""
@@ -341,8 +341,7 @@ def _stream_helper(self, response, decode=False):
341341

342342
if response.raw._fp.chunked:
343343
if decode:
344-
for chunk in json_stream(self._stream_helper(response, False)):
345-
yield chunk
344+
yield from json_stream(self._stream_helper(response, False))
346345
else:
347346
reader = response.raw
348347
while not reader.closed:
@@ -398,8 +397,7 @@ def _multiplexed_response_stream_helper(self, response):
398397
def _stream_raw_result(self, response, chunk_size=1, decode=True):
399398
''' Stream result for TTY-enabled container and raw binary data'''
400399
self._raise_for_status(response)
401-
for out in response.iter_content(chunk_size, decode):
402-
yield out
400+
yield from response.iter_content(chunk_size, decode)
403401

404402
def _read_from_socket(self, response, stream, tty=True, demux=False):
405403
socket = self._get_raw_response_socket(response)
@@ -477,7 +475,7 @@ def _unmount(self, *args):
477475

478476
def get_adapter(self, url):
479477
try:
480-
return super(APIClient, self).get_adapter(url)
478+
return super().get_adapter(url)
481479
except requests.exceptions.InvalidSchema as e:
482480
if self._custom_adapter:
483481
return self._custom_adapter

docker/api/config.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,9 @@
11
import base64
22

3-
import six
4-
53
from .. import utils
64

75

8-
class ConfigApiMixin(object):
6+
class ConfigApiMixin:
97
@utils.minimum_version('1.30')
108
def create_config(self, name, data, labels=None):
119
"""
@@ -22,8 +20,7 @@ def create_config(self, name, data, labels=None):
2220
data = data.encode('utf-8')
2321

2422
data = base64.b64encode(data)
25-
if six.PY3:
26-
data = data.decode('ascii')
23+
data = data.decode('ascii')
2724
body = {
2825
'Data': data,
2926
'Name': name,

docker/api/container.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
from datetime import datetime
22

3-
import six
4-
53
from .. import errors
64
from .. import utils
75
from ..constants import DEFAULT_DATA_CHUNK_SIZE
@@ -12,7 +10,7 @@
1210
from ..types import NetworkingConfig
1311

1412

15-
class ContainerApiMixin(object):
13+
class ContainerApiMixin:
1614
@utils.check_resource('container')
1715
def attach(self, container, stdout=True, stderr=True,
1816
stream=False, logs=False, demux=False):
@@ -408,7 +406,7 @@ def create_container(self, image, command=None, hostname=None, user=None,
408406
:py:class:`docker.errors.APIError`
409407
If the server returns an error.
410408
"""
411-
if isinstance(volumes, six.string_types):
409+
if isinstance(volumes, str):
412410
volumes = [volumes, ]
413411

414412
if isinstance(environment, dict):
@@ -790,7 +788,7 @@ def kill(self, container, signal=None):
790788
url = self._url("/containers/{0}/kill", container)
791789
params = {}
792790
if signal is not None:
793-
if not isinstance(signal, six.string_types):
791+
if not isinstance(signal, str):
794792
signal = int(signal)
795793
params['signal'] = signal
796794
res = self._post(url, params=params)

docker/api/daemon.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from .. import auth, types, utils
55

66

7-
class DaemonApiMixin(object):
7+
class DaemonApiMixin:
88
@utils.minimum_version('1.25')
99
def df(self):
1010
"""

docker/api/exec_api.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
1-
import six
2-
31
from .. import errors
42
from .. import utils
53

64

7-
class ExecApiMixin(object):
5+
class ExecApiMixin:
86
@utils.check_resource('container')
97
def exec_create(self, container, cmd, stdout=True, stderr=True,
108
stdin=False, tty=False, privileged=False, user='',
@@ -45,7 +43,7 @@ def exec_create(self, container, cmd, stdout=True, stderr=True,
4543
'Setting environment for exec is not supported in API < 1.25'
4644
)
4745

48-
if isinstance(cmd, six.string_types):
46+
if isinstance(cmd, str):
4947
cmd = utils.split_command(cmd)
5048

5149
if isinstance(environment, dict):

docker/api/image.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,13 @@
11
import logging
22
import os
33

4-
import six
5-
64
from .. import auth, errors, utils
75
from ..constants import DEFAULT_DATA_CHUNK_SIZE
86

97
log = logging.getLogger(__name__)
108

119

12-
class ImageApiMixin(object):
10+
class ImageApiMixin:
1311

1412
@utils.check_resource('image')
1513
def get_image(self, image, chunk_size=DEFAULT_DATA_CHUNK_SIZE):
@@ -130,7 +128,7 @@ def import_image(self, src=None, repository=None, tag=None, image=None,
130128

131129
params = _import_image_params(
132130
repository, tag, image,
133-
src=(src if isinstance(src, six.string_types) else None),
131+
src=(src if isinstance(src, str) else None),
134132
changes=changes
135133
)
136134
headers = {'Content-Type': 'application/tar'}
@@ -139,7 +137,7 @@ def import_image(self, src=None, repository=None, tag=None, image=None,
139137
return self._result(
140138
self._post(u, data=None, params=params)
141139
)
142-
elif isinstance(src, six.string_types): # from file path
140+
elif isinstance(src, str): # from file path
143141
with open(src, 'rb') as f:
144142
return self._result(
145143
self._post(
@@ -571,7 +569,7 @@ def tag(self, image, repository, tag=None, force=False):
571569
def is_file(src):
572570
try:
573571
return (
574-
isinstance(src, six.string_types) and
572+
isinstance(src, str) and
575573
os.path.isfile(src)
576574
)
577575
except TypeError: # a data string will make isfile() raise a TypeError

docker/api/network.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from .. import utils
55

66

7-
class NetworkApiMixin(object):
7+
class NetworkApiMixin:
88
def networks(self, names=None, ids=None, filters=None):
99
"""
1010
List networks. Similar to the ``docker network ls`` command.

docker/api/plugin.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
import six
2-
31
from .. import auth, utils
42

53

6-
class PluginApiMixin(object):
4+
class PluginApiMixin:
75
@utils.minimum_version('1.25')
86
@utils.check_resource('name')
97
def configure_plugin(self, name, options):
@@ -21,7 +19,7 @@ def configure_plugin(self, name, options):
2119
url = self._url('/plugins/{0}/set', name)
2220
data = options
2321
if isinstance(data, dict):
24-
data = ['{0}={1}'.format(k, v) for k, v in six.iteritems(data)]
22+
data = [f'{k}={v}' for k, v in data.items()]
2523
res = self._post_json(url, data=data)
2624
self._raise_for_status(res)
2725
return True

docker/api/secret.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import base64
22

3-
import six
4-
53
from .. import errors
64
from .. import utils
75

86

9-
class SecretApiMixin(object):
7+
class SecretApiMixin:
108
@utils.minimum_version('1.25')
119
def create_secret(self, name, data, labels=None, driver=None):
1210
"""
@@ -25,8 +23,7 @@ def create_secret(self, name, data, labels=None, driver=None):
2523
data = data.encode('utf-8')
2624

2725
data = base64.b64encode(data)
28-
if six.PY3:
29-
data = data.decode('ascii')
26+
data = data.decode('ascii')
3027
body = {
3128
'Data': data,
3229
'Name': name,

docker/api/service.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def raise_version_error(param, min_version):
4545
if task_template is not None:
4646
if 'ForceUpdate' in task_template and utils.version_lt(
4747
version, '1.25'):
48-
raise_version_error('force_update', '1.25')
48+
raise_version_error('force_update', '1.25')
4949

5050
if task_template.get('Placement'):
5151
if utils.version_lt(version, '1.30'):
@@ -113,7 +113,7 @@ def _merge_task_template(current, override):
113113
return merged
114114

115115

116-
class ServiceApiMixin(object):
116+
class ServiceApiMixin:
117117
@utils.minimum_version('1.24')
118118
def create_service(
119119
self, task_template, name=None, labels=None, mode=None,

docker/api/swarm.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import logging
2-
from six.moves import http_client
2+
import http.client as http_client
33
from ..constants import DEFAULT_SWARM_ADDR_POOL, DEFAULT_SWARM_SUBNET_SIZE
44
from .. import errors
55
from .. import types
@@ -8,7 +8,7 @@
88
log = logging.getLogger(__name__)
99

1010

11-
class SwarmApiMixin(object):
11+
class SwarmApiMixin:
1212

1313
def create_swarm_spec(self, *args, **kwargs):
1414
"""

docker/api/volume.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from .. import utils
33

44

5-
class VolumeApiMixin(object):
5+
class VolumeApiMixin:
66
def volumes(self, filters=None):
77
"""
88
List volumes currently registered by the docker daemon. Similar to the

0 commit comments

Comments
 (0)