-
Notifications
You must be signed in to change notification settings - Fork 0
/
.sourcery.yaml
1194 lines (1069 loc) · 42.2 KB
/
.sourcery.yaml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# 🪄 This is your project's Sourcery configuration file.
# You can use it to get Sourcery working in the way you want, such as
# ignoring specific refactorings, skipping directories in your project,
# or writing custom rules.
# 📚 For a complete reference to this file, see the documentation at
# https://docs.sourcery.ai/Reference/Configuration/sourcery-yaml/
# This file was auto-generated by Sourcery on 2022-09-08 at 15:22.
version: '1'
ignore:
- .git
- venv
- .venv
- env
- .env
- .tox
refactor:
rule_types:
- refactoring
- suggestion
- comment
python_version: '3.7'
rules:
# ==================================================================================
# [Google Python Style Guide rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/)
# ==================================================================================
#
# The following rules instruct Sourcery to help making sure that the Google Python Style
# Guide is respected in this project.
#
# The [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html) was
# created by [Google](https://github.com/google) and published under the
# [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/legalcode) license.
# ----------------------------------------------------------------------------------
# [2.2 Import Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#22-import-rules)
# ----------------------------------------------------------------------------------
#
# The rules in this section keep imports intuitive and consistent.
#
# Individual examples for these rules in action can be found at
# [examples/individual_rules/import_rules.py](./examples/individual_rules/import_rules.py)
- id: no-wildcard-imports
pattern: from ... import *
description: Do not use wildcard imports
explanation: |
Use import statements for packages and modules only, not for individual classes or functions.
- Use `import x` for importing packages and modules.
- Use `from x import y` where `x` is the package prefix and `y` is the module name with no prefix.
- Use `from x import y as z` if two modules named `y` are to be imported, if `y` conflicts with a top-level name defined in the current module, or if `y` is an inconveniently long name.
- Use `import y as z` only when `z` is a standard abbreviation (e.g., np for numpy).
From: Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
tags:
- google-python-style-guide
tests:
- match: from numpy import *
- match: from pandas.series import *
- match: from .something import *
- no-match: from math import sin
- id: no-relative-imports
description: Always use absolute imports instead of relative imports
explanation: |
Do not use relative names in imports. Even if the module is in the same package, use the full package name. This helps prevent unintentionally importing a package twice.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: from ${module} import ...
condition: module.matches_regex(r"^\.")
tags:
- google-python-style-guide
tests:
- match: from . import important_function
- match: from .my_module import important_function
- match: from ..my_module import important_function, unimportant_function
- no-match: from my_company.my_module import important_function
- no-match: from pathlib import Path
- id: use-standard-name-for-aliases-pandas
description: Import `pandas` as `pd`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., pandas as ${alias}, ...
condition: not alias.equals("pd")
tags:
- google-python-style-guide
tests:
- no-match: import pandas
- no-match: from pandas import DataFrame
- no-match: import pandas as pd
- no-match: import numpy, pandas as pd, tensorflow
- no-match: from modin import pandas as pds
- no-match: import modin.pandas as pds
- match: import pandas as pds
- match: import pandas as np
- match: import numpy, pandas as pds, tensorflow
- id: use-standard-name-for-aliases-numpy
description: Import `numpy` as `np`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., numpy as ${alias}, ...
condition: not alias.equals("np")
tags:
- google-python-style-guide
tests:
- no-match: import numpy
- no-match: from numpy import ndarray
- no-match: import numpy as np
- no-match: import pandas, numpy as np, tensorflow
- match: import numpy as numpie
- match: import numpy as pd
- match: import pandas, numpy as numpie, tensorflow
- id: use-standard-name-for-aliases-matplotlib-pyplot
description: Import `matplotlib.pyplot` as `plt`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., matplotlib.pyplot as ${alias}, ...
condition: not alias.equals("plt")
tags:
- google-python-style-guide
tests:
- no-match: import matplotlib.pyplot
- no-match: from matplotlib.pyplot import Figure
- no-match: import matplotlib.pyplot as plt
- no-match: import pandas, matplotlib.pyplot as plt, tensorflow
- match: import matplotlib.pyplot as mplplot
- match: import pandas, matplotlib.pyplot as mplplot, tensorflow
- id: use-standard-name-for-aliases-tensorflow
description: Import `tensorflow` as `tf`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., tensorflow as ${alias}, ...
condition: not alias.equals("tf")
tags:
- google-python-style-guide
tests:
- no-match: import tensorflow
- no-match: from tensorflow import keras
- no-match: import tensorflow as tf
- no-match: import pandas, tensorflow as tf
- match: import tensorflow as tflow
- match: import pandas, tensorflow as tflow
- id: use-standard-name-for-aliases-datetime
description: Import `datetime` as `dt`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., datetime as ${alias}, ...
condition: not alias.equals("dt")
tags:
- google-python-style-guide
tests:
- no-match: import datetime
- no-match: from datetime import datetime
- no-match: import datetime as dt
- no-match: import pandas, datetime as dt
- match: import datetime as dtime
- match: import pandas, datetime as dtime, tensorflow
- id: use-standard-name-for-aliases-tkinter
description: Import `tkinter` as `tk`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., tkinter as ${alias}, ...
condition: not alias.equals("tk")
tags:
- google-python-style-guide
tests:
- no-match: import tkinter
- no-match: from tkinter import ttk
- no-match: import tkinter as tk
- no-match: import pandas, tkinter as tk
- match: import tkinter as t
- match: import pandas, tkinter as t, tensorflow
- id: use-standard-name-for-aliases-multiprocessing
description: Import `multiprocessing` as `mp`
explanation: |
Use `import y as z` only when `z` is a standard abbreviation.
From Google Style Guide [2.2.4](https://google.github.io/styleguide/pyguide.html#224-decision)
pattern: import ..., multiprocessing as ${alias}, ...
condition: not alias.equals("mp")
tags:
- google-python-style-guide
tests:
- no-match: import multiprocessing
- no-match: from multiprocessing import Pool
- no-match: import multiprocessing as mp
- no-match: import pandas, multiprocessing as mp
- match: import multiprocessing as multi
- match: import pandas, multiprocessing as multi, tensorflow
# ----------------------------------------------------------------------------------
# [2.4 Exception Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#24-exception-rules)
# ----------------------------------------------------------------------------------
#
# The rule in this section ensures that exceptions are consistently named.
#
# Individual examples for this rule in action can be found at
# [examples/individual_rules/exception_rules.py](./examples/individual_rules/exception_rules.py)
- id: errors-named-error
pattern: |
class ${error}(${base}):
${statements*}
condition:
(base.is_exception_type() or base.matches_regex("[A-Z][a-zA-Z]*Error")) and not error.matches_regex("[A-Z][a-zA-Z]*Error")
description:
Exception names must end in Error
explanation: |
From Google Style Guide [2.4.4](https://google.github.io/styleguide/pyguide.html#244-decision)
tags:
- google-python-style-guide
tests:
- match: |
class Foo(ValueError):
...
- match: |
class ExampleException(CustomError):
def __init__(self, msg):
...
- match: |
class InvalidName(Exception):
...
- match: |
class InvalidName(BaseException):
...
- no-match: |
class MyError(Exception):
def __init__(self, msg):
...
- no-match: |
class NameError(AttributeError):
...
- no-match: |
class Dog(Mammal):
...
# ----------------------------------------------------------------------------------
# [2.5 Global Variable Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#25-global-variable-rules)
# ----------------------------------------------------------------------------------
#
# The rule in this section prevents global variables from being defined.
#
# Individual examples for this rule in action can be found at
# [examples/individual_rules/global_variable_rules.py](./examples/individual_rules/global_variable_rules.py)
- id: avoid-global-variables
pattern: ${var} = ${value}
condition: pattern.in_module_scope() and var.is_lower_case() and not var.starts_with("_") and var.is_identifier() and not var.contains("logger")
description: Do not define variables at the module level - (found variable ${var})
explanation: |
Avoid global variables.
If needed, global variables should be declared at the module level and made internal to the module by prepending an `_` to the name. External access to global variables must be done through public module-level functions.
While module-level constants are technically variables, they are permitted and encouraged. For example: `MAX_HOLY_HANDGRENADE_COUNT = 3`. Constants must be named using all caps with underscores.
From Google Style Guide [2.5.4](https://google.github.io/styleguide/pyguide.html#254-decision)
tags:
- google-python-style-guide
tests:
- match: max_holy_handgrenade_count = 3
- match: "max_holy_handgrenade_count: int = 3"
- no-match: holy_handgrenade[1] = 3
- no-match: _max_holy_handgrenade_count = 3
- no-match: HolyGrenades = Dict[str, Grenade]
- no-match: MAX_HOLY_HANDGRENADE_COUNT = 3
- no-match: |
def f():
max_holy_handgrenade_count = 3
# ----------------------------------------------------------------------------------
# [2.8 Default Iterator and Operator Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#28-default-iterator-and-operator-rules)
# ----------------------------------------------------------------------------------
#
# The rule in this section suggests the use of correct iterator and operator types.
#
# Individual examples for this rule in action can be found at
# [examples/individual_rules/default_iterator_and_operator_rules.py](./examples/individual_rules/default_iterator_and_operator_rules.py)
- id: do-not-use-has-key
pattern: ${d}.has_key(${key})
condition: d.has_type("dict")
replacement: ${key} in ${d}
description: Replace Python 2 syntax `dict.has_key` with a Python 3 membership test
explanation: |
Use default iterators and operators for types that support them, like lists, dictionaries, and files. The built-in types define iterator methods, too. Prefer these methods to methods that return lists, except that you should not mutate a container while iterating over it.
From Google Style Guide [2.8.4](https://google.github.io/styleguide/pyguide.html#284-decision)
Note that the method `dict.has_key` is only available in Python 2, but Sourcery only
works with Python 3 code. Hence, this rule prevents programmers from erroneously
checking membership with `dictionary.has_key(key)`, suggesting instead the use of
the correct Python 3 syntax `key in dictionary`.
tags:
- google-python-style-guide
tests:
- match: |
tasks_for_today: dict[str, Task] = get_tasks("today")
is_week_day = tasks_for_today.has_key("work")
expect: |
tasks_for_today: dict[str, Task] = get_tasks("today")
is_week_day = "work" in tasks_for_today
- match: |
def is_movie_in_database(movie: Movie, movies: Dict[Movie, MovieSpec]) -> bool:
return movies.has_key(movie)
expect: |
def is_movie_in_database(movie: Movie, movies: Dict[Movie, MovieSpec]) -> bool:
return movie in movies
- match: |
pro_users = {
user.name: user
for user in database.fetch(User)
}
if pro_users.has_key(get_current_user().name):
print("You've signed in under the PRO subscription")
else:
print("Please sign up for PRO to use this awesome feature!")
expect: |
pro_users = {
user.name: user
for user in database.fetch(User)
}
if get_current_user().name in pro_users:
print("You've signed in under the PRO subscription")
else:
print("Please sign up for PRO to use this awesome feature!")
- no-match: |
# Not sure of `random_object` is a dictionary
random_object.has_key(random_key)
- no-match: |
# Custom type `Database` is not a dictionary
database: Database = get_database()
print(database.has_key("dinosaur"))
# ----------------------------------------------------------------------------------
# [2.10 Lambda Function Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#210-lambda-function-rules)
# ----------------------------------------------------------------------------------
#
# The rules in this section ensure that `lambda`s are kept simple and short, or
# suggest the use of other, more Pythonic constructs.
#
# Individual examples for these rules in action can be found at
# [examples/individual_rules/lambda_function_rules.py](./examples/individual_rules/lambda_function_rules.py)
- id: lambdas-should-be-short
description: Lambda functions should be kept to a single line
explanation: |
Okay to use them for one-liners.
If the code inside the lambda function is longer than 60-80 chars, it’s probably better to define it as a regular nested function.
From Google Style Guide [2.10.4](https://google.github.io/styleguide/pyguide.html#2104-decision)
pattern: "lambda ...: ${body}"
condition: body.character_count() > 80
tags:
- google-python-style-guide
tests:
- no-match: "lambda x: x**2"
- no-match: "lambda x, y: x**y"
- match: "lambda x: do_something_very_long_and_involved_with(x) - do_other_very_long_and_involved_things_with(x)"
- match: "lambda x, y, z: do_something_very_long_and_involved_with(x) - do_other_very_long_and_involved_things_with(y, z)"
- id: map-lambda-to-generator
pattern: 'map(lambda ${arg}: ${expr}, ${items})'
replacement: '(${expr} for ${arg} in ${items})'
description: Replace mapping a lambda with a generator expression
explanation: |
Prefer generator expressions over map() or filter() with a lambda.
From Google Style Guide [2.10](https://google.github.io/styleguide/pyguide.html#210-lambda-functions)
tags:
- google-python-style-guide
tests:
- match: "transformed_things = map(lambda x: x**2, things)"
expect: transformed_things = (x**2 for x in things)
- match: "list(map(lambda x: x**2, things))"
expect: list(x**2 for x in things)
- no-match: "filter(lambda x: x > x**2, things)"
- id: filter-lambda-to-generator
pattern: 'filter(lambda ${arg}: ${expr}, ${items})'
replacement: '(${arg} for ${arg} in ${items} if ${expr})'
description: Replace filtering with a lambda with a generator expression
explanation: |
Prefer generator expressions over map() or filter() with a lambda.
From Google Style Guide [2.10](https://google.github.io/styleguide/pyguide.html#210-lambda-functions)
tags:
- google-python-style-guide
tests:
- match: "filtered_things = filter(lambda x: x > x**2, things)"
expect: filtered_things = (x for x in things if x > x**2)
- match: "list(filter(lambda x: x > x**2, things))"
expect: list(x for x in things if x > x**2)
- no-match: "map(lambda x: x**2, things)"
# ----------------------------------------------------------------------------------
# [2.11 Conditional Expression Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#211-conditional-expression-rules)
# ----------------------------------------------------------------------------------
#
# The rule in this section ensures conditional expressions are kept short and simple.
#
# Individual examples for this rule in action can be found at
# [examples/individual_rules/conditional_expression_rules.py](./examples/individual_rules/conditional_expression_rules.py)
- id: no-complex-if-expressions
description: Only use conditional expressions for simple cases
explanation: |
Each portion [of the conditional expression] must fit on one line: `true-expression`, `if-expression`, `else-expression`. Use a complete if statement when things get more complicated.
From Google Style Guide [2.11.4](https://google.github.io/styleguide/pyguide.html#2114-decision)
pattern: ${value} if ${test} else ${default}
condition: value.character_count() > 80 or test.character_count() > 80 or default.character_count() > 80
tags:
- google-python-style-guide
tests:
- no-match: a = 1 if cond else 2
- match: a = 1 if this_is_an_incredibly_long_condition_that_is_more_than_80_characters_long_no_joking_around else 2
- match: a = this_is_an_incredibly_long_value_that_is_more_than_80_characters_long_no_joking_around if cond else 2
- match: a = 1 if cond else this_is_an_incredibly_long_value_that_is_more_than_80_characters_long_no_joking_around
- match: a = 1 if cond else this_is_an_incredibly_long_value + is_more_than_80_characters_long_no_joking_around()
# ----------------------------------------------------------------------------------
# [2.17 Decorator Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#217-decorator-rules)
# ----------------------------------------------------------------------------------
#
# The rule in this section prevents [`staticmethod`](https://docs.python.org/3/library/functions.html#staticmethod) from being used.
#
# Individual examples for this rule in action can be found at
# [examples/individual_rules/decorator_rules.py](./examples/individual_rules/decorator_rules.py)
- id: do-not-use-staticmethod
pattern: |
@staticmethod
def ${name}(...):
...
description: Do not use the staticmethod decorator
explanation: |
Never use staticmethod unless forced to in order to integrate with an API defined in an existing library. Write a module level function instead.
From: Google Style Guide [2.17.4](https://google.github.io/styleguide/pyguide.html#2174-decision)
tags:
- google-python-style-guide
tests:
- match: |
@staticmethod
def suggested_event(new_suggestion) -> str:
pass
- match: |
@staticmethod
def suggested_event(new_suggestion: bool) -> str:
pass
- no-match: |
def suggested_event(new_suggestion) -> str:
pass
- no-match: |
@staticmethod # Note that this will not currently trigger where there are other decorators
@other_decorator
def suggested_event(new_suggestion) -> str:
pass
# ----------------------------------------------------------------------------------
# [2.21 Type Annotation Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#221-type-annotation-rules)
# ----------------------------------------------------------------------------------
#
# The rules in this section suggest the addition of type annotations to functions and
# methods.
#
# Individual examples for these rules in action can be found at
# [examples/individual_rules/type_annotations_rules.py](./examples/individual_rules/type_annotations_rules.py)
- id: require-parameter-annotation
pattern: |
def ${name}(..., ${arg}: !!!=${default?}, ...):
...
condition: not name.starts_with("_") and not arg.equals("self") and not arg.equals("cls")
paths:
exclude:
- 'test_*.py'
- '*_test.py'
description: Annotate parameter `${arg}` in public function/method `${name}` with a type annotation
explanation: |
Adding type annotations has several benefits:
1. It improves the documentation of the function
2. It allows the function to be checked for correctness
3. It allows checking that the function callers are passing the correct params
These [mypy docs](https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html#functions) describe how to
annotate function arguments and return types.
From Google Style Guide [2.21](https://google.github.io/styleguide/pyguide#221-type-annotated-code)
tags:
- google-python-style-guide
tests:
- match: |
def add(a, b: int):
return a + b
- match: |
def f(a=1):
return a * 2
- no-match: |
def f() -> int:
pass
- no-match: |
def f(a: int, b: str):
pass
- no-match: |
def f(self, a: int, b: str):
pass
- no-match: |
def f(cls, a: int, b: str):
pass
- id: require-return-annotation
pattern: |
def ${name}(...) -> !!!:
...
condition: not name.starts_with("_")
paths:
exclude:
- 'test_*.py'
- '*_test.py'
description: Annotate public function/method `${name}` with a return type annotation
explanation: |
Adding type annotations has several benefits:
1. It improves the documentation of the function
2. It allows the function to be checked for correctness
3. It allows checking that the function callers are passing the correct params
These [mypy docs](https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html#functions) describe how to
annotate function arguments and return types.
From Google Style Guide [2.21](https://google.github.io/styleguide/pyguide#221-type-annotated-code)
tags:
- google-python-style-guide
tests:
- match: |
def f():
x()
- no-match: |
def f() -> int:
x()
- match: |
def f(a: int, b: str):
x()
- no-match: |
def f(something) -> int:
x()
# ----------------------------------------------------------------------------------
# [3.8 Docstring and Comment Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#38-docstring-and-comment-rules)
# ----------------------------------------------------------------------------------
#
# The rules in this section ensure that functions, methods, classes and modules contain
# docstrings.
#
# Individual examples for these rules in action can be found at
# [examples/individual_rules/docstring_and_comment_rules.py](./examples/individual_rules/docstring_and_comment_rules.py)
- id: docstrings-for-classes
pattern: |
class ${c}(...):
"""!!!"""
...
description: Public classes should have docstrings
explanation: |
All public classes should have a docstring describing the class.
The class docstring should also document the class' public attributes.
From Google Style Guide [3.8.4](https://google.github.io/styleguide/pyguide.html#384-classes)
condition: not c.starts_with("_")
paths:
exclude:
- 'test_*.py'
- '*_test.py'
tags:
- google-python-style-guide
tests:
- match: |
class CheeseShopAddress:
...
- match: |
class CheeseShopAddress(Address):
...
- match: |
class OutOfCheeseError(Exception):
def __str__(self):
...
- no-match: |
class CheeseShopAddress:
"""The address of a cheese shop."""
- no-match: |
class OutOfCheeseError(Exception):
"""No more cheese is available."""
def __str__(self):
...
- no-match: |
class _BrieCounter:
limit: 500
- id: docstrings-for-functions
pattern: |
def ${f}(...):
"""!!!"""
${body*}
description: Functions should have docstrings
explanation: |
A function must have a docstring, unless it meets all of the following criteria:
- not externally visible
- very short
- obvious
From Google Style Guide [3.8.3](https://google.github.io/styleguide/pyguide.html#383-functions-and-methods)
condition: not ((f.starts_with("_") and body.statement_count() < 5) or pattern.in_function_scope())
paths:
exclude:
- 'test_*.py'
- '*_test.py'
tags:
- google-python-style-guide
tests:
- match: |
def grow(plant):
assert plant.is_alive()
_grow(plant)
- match: |
def _grow(plant):
pot = plant.owner.get_empty_pot()
pot.contents.add("soil", fraction=0.5)
pot.contents.add(plant, orientation="vertical")
for day in range(0, plant.__class__.gestation_time, plant.__class__.watering_interval):
pot.contents.add("water", amount="200ml")
- no-match: |
class PotContents:
def add(item, fraction=None, amount=None, **kwargs):
"""Adds `item` to the pot.
The pot can be filled to either a `fraction` of its volume, or by an `amount` specified.
"""
...
- no-match: |
def _log_growth(plant):
logger.info("plant size: %s", plant.size)
- no-match: |
def log_growth_error(f):
"""Captures and logs any growth errors inside `f`"""
def wrapped(*args, **kwargs):
try:
return f(*args, **kwargs)
except GrowthError:
logger.warning("growth error")
return wrapped
- id: docstrings-for-modules
pattern: |
'''!!!'''
...
condition: pattern.in_module_scope()
paths:
exclude:
- 'test_*.py'
- '*_test.py'
description: Modules should have docstrings
explanation: |
Modules (Python files) should start with docstrings describing the contents and usage of the module.
From Google Style Guide [3.8.2](https://google.github.io/styleguide/pyguide.html#382-modules)
tags:
- google-python-style-guide
tests:
- match: |
def hello():
print("hello")
- match: |
class Hello:
"""Hello"""
def hello():
"""Prints 'hello'"""
print("hello")
- no-match: |
"""Hello module"""
def hello():
print("hello")
# ----------------------------------------------------------------------------------
# [3.15 Getter and Setter Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#315-getter-and-setter-rules)
# ----------------------------------------------------------------------------------
#
# The rule in this section prevents the definition of trivial getters and setters (i.e.,
# methods that have no extra logic apart from reading or writing an attribute).
#
# Individual examples for this rule in action can be found at
# [examples/individual_rules/getter_and_setter_rules.py](./examples/individual_rules/getter_and_setter_rules.py)
- id: avoid-trivial-properties
description: Avoid defining trivial properties
explanation: |
Getter and setter functions (also called accessors and mutators) should be used when
they provide a meaningful role or behavior for getting or setting a variable's
value.
In particular, they should be used when getting or setting the variable is complex
or the cost is significant, either currently or in a reasonable future.
If, for example, a pair of getters/setters simply read and write an internal
attribute, the internal attribute should be made public instead. By comparison, if
setting a variable means some state is invalidated or rebuilt, it should be a setter
function. The function invocation hints that a potentially non-trivial operation is
occurring. Alternatively, properties may be an option when simple logic is needed,
or refactoring to no longer need getters and setters.
From Google Style Guide [3.15](https://google.github.io/styleguide/pyguide#315-getters-and-setters)
pattern: |
@property
def ${f}(self):
return self.${value}
...
@${f}.setter
def ${setter}(self, ${other}):
self.${value} = ${other}
tags:
- google-python-style-guide
tests:
- match: |
class Student:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, new_name):
self._name = new_name
- match: |
class Student:
def __init__(self, name, grade):
self._name = name
self._grade = grade
@property
def name(self):
return self._name
def get_grade(self):
return self._grade
@name.setter
def name(self, new_name):
self._name = new_name
- match: |
class Student:
def __init__(self, name: str) -> None:
self._name: str = name
@property
def name(self) -> str:
return self._name
@name.setter
def name(self, new_name: str) -> None:
self._name = new_name
- no-match: |
class Student:
def __init__(self, name: str) -> None:
self._name: str = name
@property
def name(self) -> str:
return self._name.title() # perform computation on name
@name.setter
def name(self, new_name: str) -> None:
self._name = new_name
- no-match: |
class Student:
def __init__(self, name: str) -> None:
self._name: str = name
@property
def name(self) -> str:
return self._name.title() # perform computation on name
# no setter: this means that `Student.name` is read-only
# ----------------------------------------------------------------------------------
# [3.16 Naming Rules](https://docs.sourcery.ai/Reference/Custom-Rules/gpsg/#316-naming-rules)
# ----------------------------------------------------------------------------------
#
# The rules in this section help ensure that variable, function and class names are
# consistent, concise and descriptive.
#
# Individual examples for these rules in action can be found at
# [examples/individual_rules/naming_rules.py](./examples/individual_rules/naming_rules.py)
- id: avoid-single-character-names-variables
pattern: ${var} = ${value}
condition: var.character_count() == 1
description: Avoid single character names
explanation: |
Avoid single character names, except for specifically allowed cases:
- counters or iterators (e.g. `i`, `j`, `k`, `v`, et al.)
- `e` as an exception identifier in `try`/`except` statements.
- `f` as a file handle in `with` statements
- private `TypeVar`s with no constraints (e.g. `_T`, `_U`, `_V`)
From Google Style Guide [3.16.1](https://google.github.io/styleguide/pyguide.html#3161-names-to-avoid)
tags:
- google-python-style-guide
tests:
- match: i = 0
- no-match: initial_value = 0
- match: A = get_account()
- no-match: account = get_account()
- no-match: |
for i in range(10):
print(i)
- no-match: |
try:
explode_computer()
except ExplosionError as e:
pass
- no-match: |
with open("file.txt") as f:
contents = f.read()
- no-match: |
from typing import TypeVar
_T = TypeVar("_T")
- id: avoid-single-character-names-functions
pattern: |
def ${function_name}(...):
...
condition: function_name.character_count() == 1
description: Avoid single character names
explanation: |
Avoid single character names, except for specifically allowed cases:
- counters or iterators (e.g. `i`, `j`, `k`, `v`, et al.)
- `e` as an exception identifier in `try`/`except` statements.
- `f` as a file handle in `with` statements
- private `TypeVar`s with no constraints (e.g. `_T`, `_U`, `_V`)
From Google Style Guide [3.16.1](https://google.github.io/styleguide/pyguide.html#3161-names-to-avoid)
tags:
- google-python-style-guide
tests:
- match: |
def f():
pass
- match: |
async def f():
pass
- no-match: |
def function_with_good_and_descriptive_name():
pass
- match: |
def g(a, b: int = 0, **kwargs) -> str:
if b > 5:
return str(a) + str(b) + str(kwargs)
return "b <= 4"
- no-match: |
def perform_calculation(a, b: int = 0, **kwargs) -> str:
if b > 5:
return str(a) + str(b) + str(kwargs)
return "b <= 4"
- match: |
class MyClass:
def m(self, a: int, b: float) -> str:
print(a)
return repr(b)
- no-match: |
class MyClass:
def good_method(self, a: int, b: float) -> str:
print(a)
return repr(b)
- id: name-type-suffix
pattern: ${name} = ${value}
condition: |
name.ends_with("_dict")
or name.ends_with("_list")
or name.ends_with("_set")
or name.ends_with("_int")
or name.ends_with("_float")
or name.ends_with("_str")
description: Don't use the type of a variable as a suffix
explanation: |
Names shouldn't needlessly include the type of the variable.
Such suffix might be OK for more complex types,
e.g. first_account, advanced_account.
But it's rarely necessary for built-in types.
From Google Style Guide [3.16.1](https://google.github.io/styleguide/pyguide.html#s3.16-naming)
tags:
- google-python-style-guide
tests:
- match: magic_int = 42
- match: magic_int = 42.00
- match: magic_float = 42
- match: magic_float = 42.00
- match: custom_notes_dict = {}
- id: snake-case-variable-declarations
pattern: |
${var}: ${type_annotation}
condition: not var.is_snake_case() and not var.in_module_scope()
description: Use snake case for variable names
explanation: |
Use snake case for variables.
This rule catches only variables that were declared with a type annotation.
From Google Style Guide [3.16.2](https://google.github.io/styleguide/pyguide.html#s3.16.2-naming-conventions) and [PEP 8](https://peps.python.org/pep-0008/#function-and-variable-names)
tags:
- google-python-style-guide
tests:
- match: |
def some_function():
miXed: int
- match: |
def some_function():
UpperCamelCase: int
- match: |
def some_function():
UpperCamelCase42: int
- match: |
def some_function():
mixed_and_underScore: int
- match: |
def some_function():
too__many__underscores: str
- match: |
def some_function():
_too__many__underscores: str
- match: |
def some_function():
___3_underscores_prefix: str
- match: |
def some_function():
double_underscore_suffix__: str
- no-match: |
def some_function():
nr: int = 42
- no-match: |
def some_function():
miXed: int = 42
- no-match: |
def some_function():
snake_nr: int = 42
- no-match: simple_NR = 42
- no-match: CONTEXT = "whatever"
- no-match: |