Skip to content

Commit 60fe6c6

Browse files
committed
Ignore pylint warnings
1 parent b215cea commit 60fe6c6

File tree

9 files changed

+107
-62
lines changed

9 files changed

+107
-62
lines changed

Diff for: python/cog/code_xforms.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def load_module_from_string(
1212
if not source or not name:
1313
return None
1414
module = types.ModuleType(name)
15-
exec(source, module.__dict__) # noqa: S102
15+
exec(source, module.__dict__) # noqa: S102 # pylint: disable=exec-used
1616
return module
1717

1818

Diff for: python/cog/command/ast_openapi_schema.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -490,8 +490,8 @@ def predict(
490490
name = resolve_name(annotation)
491491
if isinstance(annotation, ast.Subscript):
492492
# forget about other subscripts like Optional, and assume otherlib.File will still be an uri
493-
slice = resolve_name(annotation.slice)
494-
format = {"format": "uri"} if slice in ("Path", "File") else {}
493+
slice = resolve_name(annotation.slice) # pylint: disable=redefined-builtin
494+
format = {"format": "uri"} if slice in ("Path", "File") else {} # pylint: disable=redefined-builtin
495495
array_type = {"x-cog-array-type": "iterator"} if "Iterator" in name else {}
496496
display_type = (
497497
{"x-cog-array-display": "concatenate"} if "Concatenate" in name else {}
@@ -544,7 +544,7 @@ def extract_info(code: str) -> "JSONDict":
544544
kws = {}
545545
else:
546546
raise ValueError("Unexpected default value", default)
547-
input: JSONDict = {"x-order": len(properties)}
547+
input: JSONDict = {"x-order": len(properties)} # pylint: disable=redefined-builtin
548548
# need to handle other types?
549549
arg_type = OPENAPI_TYPES.get(get_annotation(arg.annotation), "string")
550550
if get_annotation(arg.annotation) in ("Path", "File"):

Diff for: python/cog/predictor.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,8 @@
5757

5858
class BasePredictor(ABC):
5959
def setup(
60-
self, weights: Optional[Union[CogFile, CogPath, str]] = None
60+
self,
61+
weights: Optional[Union[CogFile, CogPath, str]] = None, # pylint: disable=unused-argument
6162
) -> Optional[Awaitable[None]]:
6263
"""
6364
An optional method to prepare the model so multiple predictions run efficiently.
@@ -142,12 +143,12 @@ def get_weights_type(
142143
signature = inspect.signature(setup_function)
143144
if "weights" not in signature.parameters:
144145
return None
145-
Type = signature.parameters["weights"].annotation
146+
Type = signature.parameters["weights"].annotation # pylint: disable=invalid-name,redefined-outer-name
146147
# Handle Optional. It is Union[Type, None]
147148
if get_origin(Type) == Union:
148149
args = get_args(Type)
149150
if len(args) == 2 and args[1] is type(None):
150-
Type = get_args(Type)[0]
151+
Type = get_args(Type)[0] # pylint: disable=invalid-name
151152
return Type
152153

153154

@@ -248,7 +249,7 @@ def load_slim_predictor_from_ref(ref: str, method_name: str) -> BasePredictor:
248249
log.debug(f"[{module_name}] fast loader returned None")
249250
else:
250251
log.debug(f"[{module_name}] cannot use fast loader as current Python <3.9")
251-
except Exception as e:
252+
except Exception as e: # pylint: disable=broad-exception-caught
252253
log.debug(f"[{module_name}] fast loader failed: {e}")
253254
finally:
254255
if not module:
@@ -294,7 +295,10 @@ def cleanup(self) -> None:
294295
# and do it that way. convert is supposed to mutate though, so it's tricky
295296

296297

297-
def validate_input_type(type: Type[Any], name: str) -> None:
298+
def validate_input_type(
299+
type: Type[Any], # pylint: disable=redefined-builtin
300+
name: str,
301+
) -> None:
298302
if type is inspect.Signature.empty:
299303
raise TypeError(
300304
f"No input type provided for parameter `{name}`. Supported input types are: {readable_types_list(ALLOWED_INPUT_TYPES)}, or a Union or List of those types."
@@ -411,8 +415,8 @@ def get_output_type(predictor: BasePredictor) -> Type[BaseModel]:
411415

412416
input_types = get_type_hints(predict)
413417

414-
OutputType = input_types.pop("return", None)
415-
if OutputType is None:
418+
OutputType = input_types.pop("return", None) # pylint: disable=invalid-name
419+
if not OutputType:
416420
raise TypeError(
417421
"""You must set an output type. If your model can return multiple output types, you can explicitly set `Any` as the output type.
418422

Diff for: python/cog/server/clients.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ async def upload_files(
272272
When a file is encountered, it will be passed to upload_file. Any paths will be opened and converted to files.
273273
"""
274274
# skip four isinstance checks for fast text models
275-
if type(obj) == str: # noqa: E721
275+
if type(obj) == str: # noqa: E721 # pylint: disable=unidiomatic-typecheck
276276
return obj
277277
# # it would be kind of cleaner to make the default file_url
278278
# # instead of skipping entirely, we need to convert to datauri

Diff for: python/cog/server/connection.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from typing import Any, Generic, TypeVar
99

1010
X = TypeVar("X")
11-
_ForkingPickler = connection._ForkingPickler # type: ignore
11+
_ForkingPickler = connection._ForkingPickler # type: ignore # pylint: disable=protected-access
1212

1313
# based on https://github.com/python/cpython/blob/main/Lib/multiprocessing/connection.py#L364
1414

@@ -28,7 +28,7 @@ async def async_init(self) -> None:
2828
sz = 65536
2929
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, sz)
3030
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, sz)
31-
self._reader, self._writer = await asyncio.open_connection(sock=sock)
31+
self._reader, self._writer = await asyncio.open_connection(sock=sock) # pylint: disable=attribute-defined-outside-init
3232
self.started = True
3333

3434
async def _recv(self, size: int) -> io.BytesIO:

Diff for: python/cog/server/eventtypes.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
# From worker parent process
1010
#
1111
@define
12-
class PredictionInput:
12+
class PredictionInput: # pylint: disable=too-few-public-methods
1313
payload: Dict[str, Any]
1414
id: str = field(factory=lambda: secrets.token_hex(4))
1515

@@ -21,31 +21,31 @@ def from_request(cls, request: schema.PredictionRequest) -> "PredictionInput":
2121

2222

2323
@define
24-
class Cancel:
24+
class Cancel: # pylint: disable=too-few-public-methods
2525
id: str
2626

2727

2828
@define
29-
class Shutdown:
29+
class Shutdown: # pylint: disable=too-few-public-methods
3030
pass
3131

3232

3333
# From predictor child process
3434
#
3535
@define
36-
class Log:
36+
class Log: # pylint: disable=too-few-public-methods
3737
message: str
3838
source: str = field(validator=validators.in_(["stdout", "stderr"]))
3939

4040

4141
@define
42-
class PredictionMetric:
42+
class PredictionMetric: # pylint: disable=too-few-public-methods
4343
name: str
4444
value: "float | int"
4545

4646

4747
@define
48-
class PredictionOutput:
48+
class PredictionOutput: # pylint: disable=too-few-public-methods
4949
payload: Any
5050

5151

@@ -55,7 +55,7 @@ class PredictionOutputType:
5555

5656

5757
@define
58-
class Done:
58+
class Done: # pylint: disable=too-few-public-methods
5959
canceled: bool = False
6060
error: bool = False
6161
error_detail: str = ""

Diff for: python/cog/server/http.py

+20-16
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,11 @@ class MyFastAPI(FastAPI):
8080
state: MyState # type: ignore
8181

8282

83-
def add_setup_failed_routes(app: MyFastAPI, started_at: datetime, msg: str) -> None:
83+
def add_setup_failed_routes(
84+
app: MyFastAPI, # pylint: disable=redefined-outer-name
85+
started_at: datetime,
86+
msg: str,
87+
) -> None:
8488
print(msg)
8589
result = SetupResult(
8690
started_at=started_at,
@@ -128,7 +132,7 @@ async def start_shutdown() -> Any:
128132
predictor = load_slim_predictor_from_ref(predictor_ref, "predict")
129133
InputType = get_input_type(predictor)
130134
OutputType = get_output_type(predictor)
131-
except Exception:
135+
except Exception: # pylint: disable=broad-exception-caught
132136
msg = "Error while loading predictor:\n\n" + traceback.format_exc()
133137
add_setup_failed_routes(app, started_at, msg)
134138
return app
@@ -145,15 +149,15 @@ async def start_shutdown() -> Any:
145149
class PredictionRequest(schema.PredictionRequest.with_types(input_type=InputType)):
146150
pass
147151

148-
PredictionResponse = schema.PredictionResponse.with_types(
152+
PredictionResponse = schema.PredictionResponse.with_types( # pylint: disable=invalid-name
149153
input_type=InputType, output_type=OutputType
150154
)
151155

152156
http_semaphore = asyncio.Semaphore(threads)
153157

154158
if TYPE_CHECKING:
155-
P = ParamSpec("P")
156-
T = TypeVar("T")
159+
P = ParamSpec("P") # pylint: disable=invalid-name
160+
T = TypeVar("T") # pylint: disable=invalid-name
157161

158162
def limited(f: "Callable[P, Awaitable[T]]") -> "Callable[P, Awaitable[T]]":
159163
@functools.wraps(f)
@@ -167,15 +171,15 @@ async def wrapped(*args: "P.args", **kwargs: "P.kwargs") -> "T":
167171
try:
168172
trainer_ref = get_predictor_ref(config, "train")
169173
trainer = load_slim_predictor_from_ref(trainer_ref, "train")
170-
TrainingInputType = get_training_input_type(trainer)
171-
TrainingOutputType = get_training_output_type(trainer)
174+
TrainingInputType = get_training_input_type(trainer) # pylint: disable=invalid-name
175+
TrainingOutputType = get_training_output_type(trainer) # pylint: disable=invalid-name
172176

173-
class TrainingRequest(
177+
class TrainingRequest( # pylint: disable=too-few-public-methods
174178
schema.TrainingRequest.with_types(input_type=TrainingInputType)
175179
):
176180
pass
177181

178-
TrainingResponse = schema.TrainingResponse.with_types(
182+
TrainingResponse = schema.TrainingResponse.with_types( # pylint: disable=invalid-name
179183
input_type=TrainingInputType, output_type=TrainingOutputType
180184
)
181185

@@ -222,7 +226,7 @@ def cancel_training(
222226
) -> Any:
223227
return cancel(training_id)
224228

225-
except Exception as e:
229+
except Exception as e: # pylint: disable=broad-exception-caught
226230
if isinstance(e, (PredictorNotSet, FileNotFoundError)) and not is_build:
227231
pass # ignore missing train.py for backward compatibility with existing "bad" models in use
228232
else:
@@ -354,7 +358,7 @@ async def shared_predict(
354358
# [compat] If body is supplied but input is None, set it to an empty
355359
# dictionary so that later code can be simpler.
356360
if request.input is None:
357-
request.input = {}
361+
request.input = {} # pylint: disable=attribute-defined-outside-init
358362

359363
try:
360364
# Previously, we only asked PredictionRunner to handle file uploads for
@@ -444,19 +448,19 @@ def predict(...) -> output_type:
444448

445449
class Server(uvicorn.Server):
446450
def start(self) -> None:
447-
self._thread = threading.Thread(target=self.run)
451+
self._thread = threading.Thread(target=self.run) # pylint: disable=attribute-defined-outside-init
448452
self._thread.start()
449453

450454
def stop(self) -> None:
451455
log.info("stopping server")
452-
self.should_exit = True
456+
self.should_exit = True # pylint: disable=attribute-defined-outside-init
453457

454458
self._thread.join(timeout=5)
455459
if not self._thread.is_alive():
456460
return
457461

458462
log.warn("failed to exit after 5 seconds, setting force_exit")
459-
self.force_exit = True
463+
self.force_exit = True # pylint: disable=attribute-defined-outside-init
460464
self._thread.join(timeout=5)
461465
if not self._thread.is_alive():
462466
return
@@ -470,12 +474,12 @@ def is_port_in_use(port: int) -> bool:
470474
return s.connect_ex(("localhost", port)) == 0
471475

472476

473-
def signal_ignore(signum: Any, frame: Any) -> None:
477+
def signal_ignore(signum: Any, frame: Any) -> None: # pylint: disable=unused-argument
474478
log.warn("Got a signal to exit, ignoring it...", signal=signal.Signals(signum).name)
475479

476480

477481
def signal_set_event(event: threading.Event) -> Callable[[Any, Any], None]:
478-
def _signal_set_event(signum: Any, frame: Any) -> None:
482+
def _signal_set_event(signum: Any, frame: Any) -> None: # pylint: disable=unused-argument
479483
event.set()
480484

481485
return _signal_set_event

Diff for: python/cog/server/runner.py

+23-8
Original file line numberDiff line numberDiff line change
@@ -100,11 +100,17 @@ def update_time_shares(self) -> None:
100100
self._time_shares_per_prediction[prediction_id] += incurred_cost
101101
self._last_updated_time_shares = now
102102

103-
def start_tracking(self, id: str) -> None:
103+
def start_tracking(
104+
self,
105+
id: str, # pylint: disable=redefined-builtin
106+
) -> None:
104107
self.update_time_shares()
105108
self._time_shares_per_prediction[id] = 0.0
106109

107-
def end_tracking(self, id: str) -> float:
110+
def end_tracking(
111+
self,
112+
id: str, # pylint: disable=redefined-builtin
113+
) -> float:
108114
self.update_time_shares()
109115
return self._time_shares_per_prediction.pop(id)
110116

@@ -193,7 +199,7 @@ async def inner() -> SetupResult:
193199
else:
194200
status = schema.Status.SUCCEEDED
195201
self._state = WorkerState.IDLE
196-
except Exception:
202+
except Exception: # pylint: disable=broad-exception-caught
197203
logs.append(traceback.format_exc())
198204
status = schema.Status.FAILED
199205

@@ -224,7 +230,7 @@ def handle_error(task: RunnerTask) -> None:
224230
# worker state if an exception was thrown.
225231
try:
226232
raise exc
227-
except Exception:
233+
except Exception: # pylint: disable=broad-exception-caught
228234
self.log.error("caught exception while running setup", exc_info=True)
229235
if self._shutdown_event is not None:
230236
self._shutdown_event.set()
@@ -248,7 +254,10 @@ def state_from_predictions_in_flight(self) -> WorkerState:
248254
def is_busy(self) -> bool:
249255
return self._state not in {WorkerState.PROCESSING, WorkerState.IDLE}
250256

251-
def enter_predict(self, id: str) -> None:
257+
def enter_predict(
258+
self,
259+
id: str, # pylint: disable=redefined-builtin
260+
) -> None:
252261
if self.is_busy():
253262
raise InvalidStateException(
254263
f"Invalid operation: state is {self._state} (must be processing or idle)"
@@ -263,12 +272,18 @@ def enter_predict(self, id: str) -> None:
263272
self._predictions_in_flight.add(id)
264273
self._state = self.state_from_predictions_in_flight()
265274

266-
def exit_predict(self, id: str) -> None:
275+
def exit_predict(
276+
self,
277+
id: str, # pylint: disable=redefined-builtin
278+
) -> None:
267279
self._predictions_in_flight.remove(id)
268280
self._state = self.state_from_predictions_in_flight()
269281

270282
@contextlib.contextmanager
271-
def prediction_ctx(self, id: str) -> Iterator[None]:
283+
def prediction_ctx(
284+
self,
285+
id: str, # pylint: disable=redefined-builtin
286+
) -> Iterator[None]:
272287
self.enter_predict(id)
273288
try:
274289
yield
@@ -420,7 +435,7 @@ async def _read_events(self) -> None:
420435
while self._child.is_alive() and not self._terminating.is_set():
421436
# in tests this can still be running when the task is destroyed
422437
result = await self._events.recv()
423-
id, event = result
438+
id, event = result # pylint: disable=redefined-builtin
424439
if id == "LOG" and self._state == WorkerState.STARTING:
425440
id = "SETUP"
426441
if id == "LOG" and len(self._predictions_in_flight) == 1:

0 commit comments

Comments
 (0)