Skip to content
This repository was archived by the owner on May 21, 2024. It is now read-only.

Commit 8b5027d

Browse files
author
Albert
authored
Migrate codestyle to Black (#267)
* Setup repo for Black and pre-commit - Update setup.py to install developer tools automatically - pre-commit hook to format then lint automatically * Migrate codestyle to Black * [skip ci] Update contributing.md * Fix linting errors in tests. * [skip ci] update flake8 ignore list
1 parent 74a9fce commit 8b5027d

36 files changed

+1190
-512
lines changed

.pre-commit-config.yaml

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
repos:
2+
- repo: https://github.com/psf/black
3+
rev: 21.5b0
4+
hooks:
5+
- id: black
6+
language_version: python3
7+
- repo: https://gitlab.com/pycqa/flake8
8+
rev: 3.9.1
9+
hooks:
10+
- id: flake8
11+
language_version: python3

Makefile

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ src/python_pachyderm/proto: docker-build-proto
3333

3434
init:
3535
git submodule update --init
36+
python -m pip install -U pip wheel setuptools
37+
python -m pip install -e .[DEV]
38+
pre-commit install
3639

3740
ci-install:
3841
sudo apt-get update
@@ -58,7 +61,8 @@ release:
5861
twine upload dist/*
5962

6063
lint:
61-
flake8 src/python_pachyderm --exclude=src/python_pachyderm/proto --max-line-length=120 --max-doc-length=80
64+
black --check --diff .
65+
flake8 .
6266
PYTHONPATH=./src:$(PYTHONPATH) etc/proto_lint/proto_lint.py
6367

6468
.PHONY: docs docker-build-proto init ci-install ci-setup release lint

contributing.md

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,17 @@
22

33
## Getting started
44

5-
When you first clone this repo, make sure to pull submodules as well:
5+
Setup & initialize virtualenv, for example:
66

77
```bash
8-
git submodule update --init
8+
python3 -m venv venv
9+
source venv/bin/activate
10+
```
11+
12+
Run the init script which pulls submodules as well as sets up the Python project and install development tools locally:
13+
14+
```bash
15+
make init
916
```
1017

1118
## Code
@@ -46,10 +53,10 @@ Code layout, as of 7/2020:
4653

4754
### Style
4855

49-
We follow PEP-8, with slightly loosened max line lengths. You can check that
50-
your code changes match the expected style by running `make lint` locally.
51-
The linter will also run in CI and fail if there are any stylistic
52-
discrepancies.
56+
We use `black` as our Python code formatter. After running `make init`,
57+
there should be a pre-commit hook that runs `black` and `flake8` automatically.
58+
You can also check that your code changes match the expected style by running `make lint` locally.
59+
The linter will also run in CI and fail if there are any stylistic discrepancies.
5360

5461
### Rebuilding protobuf code
5562

@@ -79,32 +86,21 @@ test suite, because it tests several variants of python and pachyderm.
7986
The full test suite takes a long time to run, and will be run anyway in CI, so
8087
locally it's usually more convenient to run specific tests. To do so:
8188

82-
* Setup & initialize virtualenv
83-
* Install the dependencies specified in `tox.ini` -- as of 30-7-20, this is:
84-
* `pytest==5.3.4`
85-
* `pytest-runner==5.2`
86-
* `protobuf>=3.11.2`
87-
* `grpcio>=1.26.0`
88-
* `certifi>=2019.11.28`
89+
* Setup & initialize virtualenv if you haven't done so already
8990
* Alternatively, you can use `tox` to create a virtual environment for you:
9091
```
9192
mkdir venvdir
9293
tox --devenv venvdir -e py38 # one possible environment
9394
source ./venvdir/bin/activate # activate python environment
9495
```
95-
* Install python-pachyderm into the virtualenv: `pip install -e .`
9696
* Start the cluster to run on `localhost:30650` -- if the cluster is not
9797
exposed on `localhost`, you can use `pachctl port-forward` to proxy
9898
connections.
9999
* Run the test: `python3 -m pytest tests -k <test name>`
100100

101101
### Linting
102102

103-
To run the linter locally:
104-
105-
* Setup & initialize virtualenv
106-
* Install `flake8`
107-
* Run `make lint`
103+
To run the linter locally, run `make lint`
108104

109105
## Rebuilding API docs
110106

etc/proto_lint/proto_lint.py

Lines changed: 62 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -33,31 +33,33 @@
3333

3434
# Attributes of proto objects that are ignored, because they are built-in from
3535
# the protobuf compiler
36-
PROTO_OBJECT_BUILTINS = set([
37-
'ByteSize',
38-
'Clear',
39-
'ClearExtension',
40-
'ClearField',
41-
'CopyFrom',
42-
'DESCRIPTOR',
43-
'DiscardUnknownFields',
44-
'Extensions',
45-
'FindInitializationErrors',
46-
'FromString',
47-
'HasExtension',
48-
'HasField',
49-
'IsInitialized',
50-
'ListFields',
51-
'MergeFrom',
52-
'MergeFromString',
53-
'ParseFromString',
54-
'RegisterExtension',
55-
'SerializePartialToString',
56-
'SerializeToString',
57-
'SetInParent',
58-
'UnknownFields',
59-
'WhichOneof'
60-
])
36+
PROTO_OBJECT_BUILTINS = set(
37+
[
38+
"ByteSize",
39+
"Clear",
40+
"ClearExtension",
41+
"ClearField",
42+
"CopyFrom",
43+
"DESCRIPTOR",
44+
"DiscardUnknownFields",
45+
"Extensions",
46+
"FindInitializationErrors",
47+
"FromString",
48+
"HasExtension",
49+
"HasField",
50+
"IsInitialized",
51+
"ListFields",
52+
"MergeFrom",
53+
"MergeFromString",
54+
"ParseFromString",
55+
"RegisterExtension",
56+
"SerializePartialToString",
57+
"SerializeToString",
58+
"SetInParent",
59+
"UnknownFields",
60+
"WhichOneof",
61+
]
62+
)
6163

6264
# A list of methods that we do not expect the library to implement
6365
BLACKLISTED_METHODS = {
@@ -129,7 +131,7 @@
129131
"list_i_d_p_connectors": ["list_idp_connectors"],
130132
"create_i_d_p_connector": ["create_idp_connector"],
131133
"update_i_d_p_connector": ["update_idp_connector"],
132-
"get_o_i_d_c_client": ["get_oidc_client"],
134+
"get_o_i_d_c_client": ["get_oidc_client"],
133135
"delete_o_i_d_c_client": ["delete_oidc_client"],
134136
"list_o_i_d_c_clients": ["list_oidc_clients"],
135137
"create_o_i_d_c_client": ["create_oidc_client"],
@@ -147,7 +149,7 @@
147149
},
148150
Service.VERSION: {
149151
"get_version": ["get_remote_version"],
150-
}
152+
},
151153
}
152154

153155
# Mapping of renamed method arguments. Multiple times of remappings are
@@ -334,17 +336,23 @@
334336
],
335337
}
336338

339+
337340
def camel_to_snake(s):
338341
"""Converts CamelCase strings to snake_case"""
339-
return s[0].lower() + "".join("_{}".format(c.lower()) if c in UPPERCASE else c for c in s[1:])
342+
return s[0].lower() + "".join(
343+
"_{}".format(c.lower()) if c in UPPERCASE else c for c in s[1:]
344+
)
345+
340346

341347
def attrs(obj):
342348
"""Gets the non-private attributes of an object"""
343349
return [m for m in dir(obj) if not m.startswith("_")]
344350

351+
345352
def trim_suffix(s, suffix):
346353
"""Removes a suffix from a string if it exists"""
347-
return s[:-len(suffix)] if s.endswith(suffix) else s
354+
return s[: -len(suffix)] if s.endswith(suffix) else s
355+
348356

349357
def args_set(values):
350358
s = set()
@@ -358,11 +366,16 @@ def args_set(values):
358366

359367
return s
360368

369+
361370
def lint_method(mixin_cls, proto_module, grpc_method_name, mixin_method_name):
362371
# get the mixin function and its arguments
363-
request_cls = getattr(proto_module, "{}Request".format(trim_suffix(grpc_method_name, "Stream")), None)
372+
request_cls = getattr(
373+
proto_module, "{}Request".format(trim_suffix(grpc_method_name, "Stream")), None
374+
)
364375
mixin_method = getattr(mixin_cls, mixin_method_name)
365-
mixin_method_args = set(a for a in inspect.getfullargspec(mixin_method).args if a != "self")
376+
mixin_method_args = set(
377+
a for a in inspect.getfullargspec(mixin_method).args if a != "self"
378+
)
366379

367380
# give a warning for a python function that takes in arguments even
368381
# though there's no request object for the gRPC function, implying
@@ -373,7 +386,9 @@ def lint_method(mixin_cls, proto_module, grpc_method_name, mixin_method_name):
373386
return
374387

375388
# find which arguments differ between the python and gRPC implementation
376-
request_args = set([n for n in attrs(request_cls) if n not in PROTO_OBJECT_BUILTINS])
389+
request_args = set(
390+
[n for n in attrs(request_cls) if n not in PROTO_OBJECT_BUILTINS]
391+
)
377392
missing_args = request_args - mixin_method_args
378393
extra_args = mixin_method_args - request_args
379394

@@ -387,6 +402,7 @@ def lint_method(mixin_cls, proto_module, grpc_method_name, mixin_method_name):
387402
for arg in missing_args - ok_missing_args:
388403
yield "method {}: missing argument: {}".format(mixin_method_name, arg)
389404

405+
390406
def lint_service(service):
391407
"""Lints a given service"""
392408

@@ -397,7 +413,9 @@ def lint_service(service):
397413
grpc_method_names = set(attrs(grpc_cls))
398414

399415
for grpc_method_name in grpc_method_names:
400-
if (not grpc_method_name.endswith("Stream")) and "{}Stream".format(grpc_method_name) in grpc_method_names:
416+
if (not grpc_method_name.endswith("Stream")) and "{}Stream".format(
417+
grpc_method_name
418+
) in grpc_method_names:
401419
# skip methods with a streaming equivalent, since only the
402420
# streaming equivalent is implemented
403421
continue
@@ -410,17 +428,24 @@ def lint_service(service):
410428
continue
411429

412430
# find if this method is renamed
413-
renamed_mixin_method_names = RENAMED_METHODS.get(service, {}).get(mixin_method_name, [mixin_method_name])
431+
renamed_mixin_method_names = RENAMED_METHODS.get(service, {}).get(
432+
mixin_method_name, [mixin_method_name]
433+
)
414434

415435
for mixin_method_name in renamed_mixin_method_names:
416436
# find if this method isn't implemented
417437
if mixin_method_name not in mixin_method_names:
418-
yield "service {}: missing method: {}".format(service.name, mixin_method_name)
438+
yield "service {}: missing method: {}".format(
439+
service.name, mixin_method_name
440+
)
419441
continue
420442

421-
for warning in lint_method(mixin_cls, proto_module, grpc_method_name, mixin_method_name):
443+
for warning in lint_method(
444+
mixin_cls, proto_module, grpc_method_name, mixin_method_name
445+
):
422446
yield "service {}: {}".format(service.name, warning)
423447

448+
424449
def main():
425450
warned = False
426451

@@ -431,5 +456,6 @@ def main():
431456

432457
sys.exit(1 if warned else 0)
433458

459+
434460
if __name__ == "__main__":
435461
main()

examples/jupyter/merge.py

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55

66
PRICE = 5
77

8+
89
def main():
910
try:
1011
weather_filenames = os.listdir("/pfs/weather")
11-
except:
12+
except FileNotFoundError:
1213
weather_filenames = []
1314

1415
with open("/pfs/out/data.csv", "w") as out_file:
@@ -19,16 +20,21 @@ def main():
1920
trip_filepath = "/pfs/trips/{}-{}".format(dt.month, dt.strftime("%d-%y"))
2021

2122
if os.path.exists(trip_filepath):
22-
with open("/pfs/weather/{}".format(weather_filename), "r") as weather_file:
23+
with open(
24+
"/pfs/weather/{}".format(weather_filename), "r"
25+
) as weather_file:
2326
with open(trip_filepath, "r") as trip_file:
2427
weather_json = json.load(weather_file)
2528
precip = weather_json["daily"]["data"][0]["precipProbability"]
2629

2730
trip_csv = csv.reader(trip_file)
28-
next(trip_csv) # skip the header row
31+
next(trip_csv) # skip the header row
2932
trips = int(next(trip_csv)[1])
3033

31-
writer.writerow([dt.strftime("%Y-%m-%d"), precip, trips, trips * PRICE])
34+
writer.writerow(
35+
[dt.strftime("%Y-%m-%d"), precip, trips, trips * PRICE]
36+
)
37+
3238

3339
if __name__ == "__main__":
3440
main()

examples/opencv/edges/main.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,19 @@
22
import numpy as np
33
from matplotlib import pyplot as plt
44
import os
5-
5+
6+
67
# make_edges reads an image from /pfs/images and outputs the result of running
78
# edge detection on that image to /pfs/out. Note that /pfs/images and
89
# /pfs/out are special directories that Pachyderm injects into the container.
910
def make_edges(image):
1011
img = cv2.imread(image)
1112
tail = os.path.split(image)[1]
12-
edges = cv2.Canny(img,100,200)
13-
plt.imsave(os.path.join("/pfs/out", os.path.splitext(tail)[0]+'.png'), edges, cmap = 'gray')
13+
edges = cv2.Canny(img, 100, 200)
14+
plt.imsave(
15+
os.path.join("/pfs/out", os.path.splitext(tail)[0] + ".png"), edges, cmap="gray"
16+
)
17+
1418

1519
# walk /pfs/images and call make_edges on every file found
1620
for dirpath, dirs, files in os.walk("/pfs/images"):

0 commit comments

Comments
 (0)