Skip to content

Commit 1f3b9c3

Browse files
committed
change: enable line-too-long Pylint check
This commit is mostly docstring length reformatting, with 2 string reformats.
1 parent 356283e commit 1f3b9c3

24 files changed

+507
-400
lines changed

.pylintrc

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ disable=
8383
too-many-arguments,
8484
invalid-name,
8585
too-many-instance-attributes,
86-
line-too-long, # We let Flake8 take care of this # TODO: Fix these and stop relying on flake8
8786
len-as-condition, # TODO: Enable this check once pylint 2.4.0 is released and consumed due to the fix in https://github.com/PyCQA/pylint/issues/2684
8887
import-error, # Since we run Pylint before any of our builds in tox, this will always fail
8988
protected-access, # TODO: Fix access
@@ -228,8 +227,9 @@ max-nested-blocks=5
228227
# Maximum number of characters on a single line.
229228
max-line-length=100
230229

231-
# Regexp for a line that is allowed to be longer than the limit.
232-
ignore-long-lines=^\s*(# )?<?https?://\S+>?$
230+
# Regexp for a line that is allowed to be longer than the limit. Can only be a single regex.
231+
# The following matches any semblance of a url of any sort.
232+
ignore-long-lines=^\s*.*(# )?(<?https?:\/\/)?[-a-zA-Z0-9@:%%._\+~#=><]{1,256}\.[a-zA-Z0-9()]{1,6}\b[-a-zA-Z0-9()@:%%_\+.~#?&\/\/=<>]*\S*>?$
233233

234234
# Allow the body of an if to be on the same line as the test if there is no
235235
# else.

src/sagemaker/algorithm.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def __init__(
128128
(default: None). If specified, the estimator will create a channel pointing to
129129
the model so the training job can download it. This model
130130
can be a 'model.tar.gz' from a previous training job, or
131-
other artifacts coming from a different source. More
131+
other artifacts coming from a different source.
132132
More information:
133133
https://docs.aws.amazon.com/sagemaker/latest/dg/cdf-training.html#td-deserialization
134134

src/sagemaker/amazon/linear_learner.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ class LinearLearner(AmazonAlgorithmEstimatorBase):
8383
"softmax_loss",
8484
"auto",
8585
),
86-
'"logistic", "squared_loss", "absolute_loss", "hinge_loss", "eps_insensitive_squared_loss", '
87-
'"eps_insensitive_absolute_loss", "quantile_loss", "huber_loss", "softmax_loss" or "auto"',
86+
'"logistic", "squared_loss", "absolute_loss", "hinge_loss", "eps_insensitive_squared_loss",'
87+
' "eps_insensitive_absolute_loss", "quantile_loss", "huber_loss", "softmax_loss" or "auto"',
8888
str,
8989
)
9090
wd = hp("wd", ge(0), "A float greater-than or equal to 0", float)
@@ -369,7 +369,8 @@ def __init__(
369369
num_classes is None or num_classes < 3
370370
):
371371
raise ValueError(
372-
"For predictor_type 'multiclass_classifier', 'num_classes' should be set to a value greater than 2."
372+
"For predictor_type 'multiclass_classifier', 'num_classes' should be set to a "
373+
"value greater than 2."
373374
)
374375

375376
def create_model(self, vpc_config_override=VPC_CONFIG_DEFAULT):

src/sagemaker/analytics.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ def description(self, force_refresh=False):
176176
if force_refresh:
177177
self.clear_cache()
178178
if not self._tuning_job_describe_result:
179-
self._tuning_job_describe_result = self._sage_client.describe_hyper_parameter_tuning_job(
179+
self._tuning_job_describe_result = self._sage_client.describe_hyper_parameter_tuning_job( # pylint: disable=line-too-long
180180
HyperParameterTuningJobName=self.name
181181
)
182182
return self._tuning_job_describe_result
@@ -288,10 +288,12 @@ def _determine_timeinterval(self):
288288
description = self._sage_client.describe_training_job(TrainingJobName=self.name)
289289
start_time = self._start_time or description[u"TrainingStartTime"] # datetime object
290290
# Incrementing end time by 1 min since CloudWatch drops seconds before finding the logs.
291-
# This results in logs being searched in the time range in which the correct log line was not present.
291+
# This results in logs being searched in the time range in which the correct log line was
292+
# not present.
292293
# Example - Log time - 2018-10-22 08:25:55
293-
# Here calculated end time would also be 2018-10-22 08:25:55 (without 1 min addition)
294-
# CW will consider end time as 2018-10-22 08:25 and will not be able to search the correct log.
294+
# Here calculated end time would also be 2018-10-22 08:25:55 (without 1 min addition)
295+
# CW will consider end time as 2018-10-22 08:25 and will not be able to search the
296+
# correct log.
295297
end_time = self._end_time or description.get(
296298
u"TrainingEndTime", datetime.datetime.utcnow()
297299
) + datetime.timedelta(minutes=1)

src/sagemaker/estimator.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -279,15 +279,13 @@ def fit(self, inputs=None, wait=True, logs=True, job_name=None):
279279
280280
* (str) the S3 location where training data is saved.
281281
282-
* (dict[str, str] or dict[str, sagemaker.session.s3_input]) If using multiple channels for
283-
training data, you can specify a dict mapping channel
284-
names to strings or :func:`~sagemaker.session.s3_input`
285-
objects.
286-
287-
* (sagemaker.session.s3_input) - channel configuration for S3 data sources that can provide
288-
additional information as well as the path to the training
289-
dataset. See :func:`sagemaker.session.s3_input` for full
290-
details.
282+
* (dict[str, str] or dict[str, sagemaker.session.s3_input]) If using multiple
283+
channels for training data, you can specify a dict mapping channel names to
284+
strings or :func:`~sagemaker.session.s3_input` objects.
285+
286+
* (sagemaker.session.s3_input) - channel configuration for S3 data sources that can
287+
provide additional information as well as the path to the training dataset.
288+
See :func:`sagemaker.session.s3_input` for full details.
291289
wait (bool): Whether the call should wait until the job completes
292290
(default: True).
293291
logs (bool): Whether to show the logs produced by the job. Only
@@ -990,9 +988,9 @@ def create_model(
990988
):
991989
"""Create a model to deploy.
992990
993-
The serializer, deserializer, content_type, and accept arguments are only used to define a default
994-
RealTimePredictor. They are ignored if an explicit predictor class is passed in. Other arguments
995-
are passed through to the Model class.
991+
The serializer, deserializer, content_type, and accept arguments are only used to define a
992+
default RealTimePredictor. They are ignored if an explicit predictor class is passed in.
993+
Other arguments are passed through to the Model class.
996994
997995
Args:
998996
role (str): The ``ExecutionRoleArn`` IAM Role ARN for the ``Model``,

src/sagemaker/fw_utils.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,9 @@ def create_image_uri(
185185
else:
186186
family = instance_type.split(".")[1]
187187

188-
# For some frameworks, we have optimized images for specific families, e.g c5 or p3. In those cases,
189-
# we use the family name in the image tag. In other cases, we use 'cpu' or 'gpu'.
188+
# For some frameworks, we have optimized images for specific families, e.g c5 or p3.
189+
# In those cases, we use the family name in the image tag. In other cases, we use
190+
# 'cpu' or 'gpu'.
190191
if family in optimized_families:
191192
device_type = family
192193
elif family[0] in ["g", "p"]:
@@ -340,6 +341,7 @@ def _list_files_to_compress(script, directory):
340341

341342

342343
def framework_name_from_image(image_name):
344+
# noinspection LongLine
343345
"""Extract the framework and Python version from the image name.
344346
345347
Args:
@@ -357,15 +359,15 @@ def framework_name_from_image(image_name):
357359
tuple: A tuple containing:
358360
str: The framework name str: The Python version str: The image tag
359361
str: If the image is script mode
360-
"""
362+
"""
361363
sagemaker_pattern = re.compile(ECR_URI_PATTERN)
362364
sagemaker_match = sagemaker_pattern.match(image_name)
363365
if sagemaker_match is None:
364366
return None, None, None, None
365367
# extract framework, python version and image tag
366368
# We must support both the legacy and current image name format.
367369
name_pattern = re.compile(
368-
r"^(?:sagemaker(?:-rl)?-)?(tensorflow|mxnet|chainer|pytorch|scikit-learn)(?:-)?(scriptmode|training)?:(.*)-(.*?)-(py2|py3)$" # noqa: E501
370+
r"^(?:sagemaker(?:-rl)?-)?(tensorflow|mxnet|chainer|pytorch|scikit-learn)(?:-)?(scriptmode|training)?:(.*)-(.*?)-(py2|py3)$" # noqa: E501 # pylint: disable=line-too-long
369371
)
370372
legacy_name_pattern = re.compile(r"^sagemaker-(tensorflow|mxnet)-(py2|py3)-(cpu|gpu):(.*)$")
371373

src/sagemaker/local/entities.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,8 @@ def _get_container_environment(self, **kwargs):
256256
# we only do 1 max concurrent transform in Local Mode
257257
if "MaxConcurrentTransforms" in kwargs and int(kwargs["MaxConcurrentTransforms"]) > 1:
258258
logger.warning(
259-
"Local Mode only supports 1 ConcurrentTransform. Setting MaxConcurrentTransforms to 1"
259+
"Local Mode only supports 1 ConcurrentTransform. Setting MaxConcurrentTransforms "
260+
"to 1"
260261
)
261262
environment["SAGEMAKER_MAX_CONCURRENT_TRANSFORMS"] = "1"
262263

@@ -287,8 +288,9 @@ def _get_required_defaults(self, **kwargs):
287288

288289
def _get_working_directory(self):
289290
"""Placeholder docstring"""
290-
# Root dir to use for intermediate data location. To make things simple we will write here regardless
291-
# of the final destination. At the end the files will either be moved or uploaded to S3 and deleted.
291+
# Root dir to use for intermediate data location. To make things simple we will write here
292+
# regardless of the final destination. At the end the files will either be moved or
293+
# uploaded to S3 and deleted.
292294
root_dir = get_config_value("local.container_root", self.local_session.config)
293295
if root_dir:
294296
root_dir = os.path.abspath(root_dir)
@@ -313,8 +315,8 @@ def _prepare_data_transformation(self, input_data, batch_strategy):
313315

314316
def _perform_batch_inference(self, input_data, output_data, **kwargs):
315317
# Transform the input data to feed the serving container. We need to first gather the files
316-
# from S3 or Local FileSystem. Split them as required (Line, RecordIO, None) and finally batch them
317-
# according to the batch strategy and limit the request size.
318+
# from S3 or Local FileSystem. Split them as required (Line, RecordIO, None) and finally
319+
# batch them according to the batch strategy and limit the request size.
318320

319321
"""
320322
Args:

src/sagemaker/local/image.py

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -81,8 +81,8 @@ def __init__(self, instance_type, instance_count, image, sagemaker_session=None)
8181
self.instance_type = instance_type
8282
self.instance_count = instance_count
8383
self.image = image
84-
# Since we are using a single docker network, Generate a random suffix to attach to the container names.
85-
# This way multiple jobs can run in parallel.
84+
# Since we are using a single docker network, Generate a random suffix to attach to the
85+
# container names. This way multiple jobs can run in parallel.
8686
suffix = "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(5))
8787
self.hosts = [
8888
"{}-{}-{}".format(CONTAINER_PREFIX, i, suffix)
@@ -160,8 +160,8 @@ def train(self, input_data_config, output_data_config, hyperparameters, job_name
160160
dirs_to_delete = [data_dir, shared_dir]
161161
self._cleanup(dirs_to_delete)
162162

163-
# Print our Job Complete line to have a similar experience to training on SageMaker where you
164-
# see this line at the end.
163+
# Print our Job Complete line to have a similar experience to training on SageMaker where
164+
# you see this line at the end.
165165
print("===== Job Complete =====")
166166
return artifacts
167167

@@ -702,10 +702,10 @@ def _delete_tree(path):
702702
try:
703703
shutil.rmtree(path)
704704
except OSError as exc:
705-
# on Linux, when docker writes to any mounted volume, it uses the container's user. In most cases
706-
# this is root. When the container exits and we try to delete them we can't because root owns those
707-
# files. We expect this to happen, so we handle EACCESS. Any other error we will raise the
708-
# exception up.
705+
# on Linux, when docker writes to any mounted volume, it uses the container's user. In most
706+
# cases this is root. When the container exits and we try to delete them we can't because
707+
# root owns those files. We expect this to happen, so we handle EACCESS. Any other error
708+
# we will raise the exception up.
709709
if exc.errno == errno.EACCES:
710710
logger.warning("Failed to delete: %s Please remove it manually.", path)
711711
else:
@@ -724,13 +724,14 @@ def _aws_credentials(session):
724724
secret_key = creds.secret_key
725725
token = creds.token
726726

727-
# The presence of a token indicates the credentials are short-lived and as such are risky to be used as they
728-
# might expire while running.
727+
# The presence of a token indicates the credentials are short-lived and as such are risky
728+
# to be used as they might expire while running.
729729
# Long-lived credentials are available either through
730730
# 1. boto session
731-
# 2. EC2 Metadata Service (SageMaker Notebook instances or EC2 instances with roles attached them)
732-
# Short-lived credentials available via boto session are permitted to support running on machines with no
733-
# EC2 Metadata Service but a warning is provided about their danger
731+
# 2. EC2 Metadata Service (SageMaker Notebook instances or EC2 instances with roles
732+
# attached them)
733+
# Short-lived credentials available via boto session are permitted to support running on
734+
# machines with no EC2 Metadata Service but a warning is provided about their danger
734735
if token is None:
735736
logger.info("Using the long-lived AWS credentials found in session")
736737
return [
@@ -739,15 +740,17 @@ def _aws_credentials(session):
739740
]
740741
if not _aws_credentials_available_in_metadata_service():
741742
logger.warning(
742-
"Using the short-lived AWS credentials found in session. They might expire while running."
743+
"Using the short-lived AWS credentials found in session. They might expire while "
744+
"running."
743745
)
744746
return [
745747
"AWS_ACCESS_KEY_ID=%s" % (str(access_key)),
746748
"AWS_SECRET_ACCESS_KEY=%s" % (str(secret_key)),
747749
"AWS_SESSION_TOKEN=%s" % (str(token)),
748750
]
749751
logger.info(
750-
"No AWS credentials found in session but credentials from EC2 Metadata Service are available."
752+
"No AWS credentials found in session but credentials from EC2 Metadata Service are "
753+
"available."
751754
)
752755
return None
753756
except Exception as e: # pylint: disable=broad-except

src/sagemaker/local/local_session.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,8 @@ def create_training_job(
8282
OutputDataConfig(dict): Identifies the location where you want to save the results of
8383
model training.
8484
ResourceConfig(dict): Identifies the resources to use for local model training.
85-
HyperParameters(dict) [optional]: Specifies these algorithm-specific parameters to influence the
86-
quality of
87-
the final model.
85+
HyperParameters(dict) [optional]: Specifies these algorithm-specific parameters to
86+
influence the quality of the final model.
8887
**kwargs:
8988
9089
Returns:

src/sagemaker/model.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -406,9 +406,9 @@ def deploy(
406406
this model completes (default: True).
407407
408408
Returns:
409-
callable[string, sagemaker.session.Session] or None: Invocation of ``self.predictor_cls`` on
410-
the created endpoint name, if ``self.predictor_cls`` is not
411-
None. Otherwise, return None.
409+
callable[string, sagemaker.session.Session] or None: Invocation of
410+
``self.predictor_cls`` on the created endpoint name, if ``self.predictor_cls``
411+
is not None. Otherwise, return None.
412412
"""
413413
if not self.sagemaker_session:
414414
if instance_type in ("local", "local_gpu"):

src/sagemaker/mxnet/estimator.py

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -86,17 +86,15 @@ def __init__(
8686
your model training code. List of supported versions
8787
https://github.com/aws/sagemaker-python-sdk#mxnet-sagemaker-estimators.
8888
If not specified, this will default to 1.2.1.
89-
image_name (str): If specified, the estimator will use this image for training and hosting, instead of
90-
selecting the appropriate SageMaker official image based on
91-
framework_version and py_version. It can be an ECR url or
92-
dockerhub image and tag.
93-
94-
Examples:
95-
123.dkr.ecr.us-west-2.amazonaws.com/my-custom-image:1.0
96-
custom-image:latest.
97-
98-
distributions (dict): A dictionary with information on how to run distributed training
99-
(default: None).
89+
image_name (str): If specified, the estimator will use this image for training and
90+
hosting, instead of selecting the appropriate SageMaker official image based on
91+
framework_version and py_version. It can be an ECR url or dockerhub image and tag.
92+
Examples:
93+
123.dkr.ecr.us-west-2.amazonaws.com/my-custom-image:1.0
94+
custom-image:latest.
95+
96+
distributions (dict): A dictionary with information on how to run distributed
97+
training (default: None).
10098
distributions:
10199
**kwargs: Additional kwargs passed to the
102100
:class:`~sagemaker.estimator.Framework` constructor.
@@ -203,10 +201,10 @@ class constructor
203201

204202
init_params["py_version"] = py_version
205203

206-
# We switched image tagging scheme from regular image version (e.g. '1.0') to more expressive
207-
# containing framework version, device type and python version (e.g. '0.12-gpu-py2').
208-
# For backward compatibility map deprecated image tag '1.0' to a '0.12' framework version
209-
# otherwise extract framework version from the tag itself.
204+
# We switched image tagging scheme from regular image version (e.g. '1.0') to more
205+
# expressive containing framework version, device type and python version
206+
# (e.g. '0.12-gpu-py2'). For backward compatibility map deprecated image tag '1.0' to a
207+
# '0.12' framework version otherwise extract framework version from the tag itself.
210208
init_params["framework_version"] = (
211209
"0.12" if tag == "1.0" else framework_version_from_tag(tag)
212210
)

src/sagemaker/parameter.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -140,8 +140,8 @@ def as_json_range(self, name):
140140
name (str): The name of the hyperparameter.
141141
142142
Returns:
143-
dict[str, list[str]]: A dictionary that contains the name and values of the hyperparameter,
144-
where the values are serialized as JSON.
143+
dict[str, list[str]]: A dictionary that contains the name and values of the
144+
hyperparameter, where the values are serialized as JSON.
145145
"""
146146
return {"Name": name, "Values": [json.dumps(v) for v in self.values]}
147147

src/sagemaker/pipeline.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,9 @@ def deploy(
112112
model completes (default: True).
113113
114114
Returns:
115-
callable[string, sagemaker.session.Session] or None: Invocation of ``self.predictor_cls`` on
116-
the created endpoint name, if ``self.predictor_cls`` is not
117-
None. Otherwise, return None.
115+
callable[string, sagemaker.session.Session] or None: Invocation of
116+
``self.predictor_cls`` on the created endpoint name, if ``self.predictor_cls``
117+
is not None. Otherwise, return None.
118118
"""
119119
if not self.sagemaker_session:
120120
self.sagemaker_session = Session()

0 commit comments

Comments
 (0)