Completed
Push — master ( 652866...ac3ef3 )
by De
01:15
created

main()   F

Complexity

Conditions 9

Size

Total Lines 121

Duplication

Lines 0
Ratio 0 %

Importance

Changes 13
Bugs 0 Features 2
Metric Value
c 13
b 0
f 2
dl 0
loc 121
rs 3.1304
cc 9

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
# -*- coding: utf-8
2
"""Code to generate examples in README.md."""
3
from didyoumean_internal import add_suggestions_to_exception
4
import didyoumean_common_tests as common
5
import os
6
7
8
def standardise(string):
9
    """Standardise string by removing elements from the environment.
10
11
    Replace strings from the environment by the name of the environment
12
    variable.
13
    """
14
    for var in ['USER']:
15
        val = os.environ.get(var)
16
        if val is not None:
17
            string = string.replace(val, var.lower())
18
    return string
19
20
21
def main():
22
    """Main."""
23
    # Different examples :
24
    # Code examples are groupes by error type then by suggestion type
25
    # Numbers have been added in dict keys just to be able to iterate
26
    # over them and have the result in the wanted order.
27
    examples = {
28
        (1, NameError): {
29
            (1, "Fuzzy matches on existing names "
30
                "(local, builtin, keywords, modules, etc)"): [
31
                "def my_func(foo, bar):\n\treturn foob\nmy_func(1, 2)",
32
                "leng([0])",
33
                "import math\nmaths.pi",
34
                "passs",
35
                "def my_func():\n\tfoo = 1\n\tfoob +=1\nmy_func()"
36
            ],
37
            (2, "Checking if name is the attribute of a defined object"): [
38
                "class Duck():\n\tdef __init__(self):\n\t\tquack()"
39
                "\n\tdef quack(self):\n\t\tpass\nd = Duck()",
40
                "import math\npi",
41
            ],
42
            (3, "Looking for missing imports"): [
43
                "string.ascii_lowercase",
44
            ],
45
            (4, "Looking in missing imports"): [
46
                "choice",
47
            ],
48
            (5, "Special cases"): [
49
                "assert j ** 2 == -1",
50
            ],
51
        },
52
        (2, AttributeError): {
53
            (1, "Fuzzy matches on existing attributes"): [
54
                "lst = [1, 2, 3]\nlst.appendh(4)",
55
                "import math\nmath.pie",
56
            ],
57
            (2, "Detection of mis-used builtins"): [
58
                "lst = [1, 2, 3]\nlst.max()",
59
            ],
60
            (3, "Trying to find method with similar meaning (hardcoded)"): [
61
                "lst = [1, 2, 3]\nlst.add(4)",
62
            ],
63
        },
64
        (3, ImportError): {
65
            (1, "Fuzzy matches on existing modules"): [
66
                "from maths import pi",
67
            ],
68
            (2, "Fuzzy matches on elements of the module"): [
69
                "from math import pie",
70
            ],
71
            (3, "Looking for import from wrong module"): [
72
                "from itertools import pi",
73
            ],
74
        },
75
        (4, TypeError): {
76
            (1, "Fuzzy matches on keyword arguments"): [
77
                "def my_func(abcde):\n\tpass\nmy_func(abcdf=1)",
78
            ],
79
            (2, "Confusion between brackets and parenthesis"): [
80
                "lst = [1, 2, 3]\nlst(0)",
81
                "def my_func(a):\n\tpass\nmy_func[1]",
82
            ],
83
        },
84
        (5, ValueError): {
85
            (1, "Special cases"): [
86
                "'Foo{}'.format('bar')",
87
            ],
88
        },
89
        (6, SyntaxError): {
90
            (1, "Fuzzy matches when importing from __future__"): [
91
                "from __future__ import divisio",
92
            ],
93
            (2, "Various"): [
94
                "return",
95
            ],
96
        },
97
        (7, MemoryError): {
98
            (1, "Search for a memory-efficient equivalent"): [
99
                "range(999999999999999)",
100
            ],
101
        },
102
        (8, OverflowError): {
103
            (1, "Search for a memory-efficient equivalent"): [
104
                "range(999999999999999)",
105
            ],
106
        },
107
        (9, (OSError, IOError)): {
108
            (1, "Suggestion for tilde/variable expansions"): [
109
                "os.listdir('~')",
110
            ]
111
        }
112
    }
113
114
    str_func = repr  # could be str or repr
115
    for (_, exc_types), exc_examples in sorted(examples.items()):
116
        if not isinstance(exc_types, tuple):
117
            exc_types = (exc_types, )
118
        print("### {0}\n".format("/".join(e.__name__ for e in exc_types)))
119
        for (_, desc), codes in sorted(exc_examples.items()):
120
            print("##### {0}\n".format(desc))
121
            for code in codes:
122
                exc = common.get_exception(code)
123
                if exc is None:
124
                    before = after = \
125
                        "No exception thrown on this version of Python"
126
                else:
127
                    type_, value, traceback = exc
128
                    if not issubclass(type_, exc_types):
129
                        before = after = \
130
                            "Wrong exception thrown on this version of Python"
131
                    else:
132
                        before = standardise(str_func(value))
133
                        add_suggestions_to_exception(type_, value, traceback)
134
                        after = standardise(str_func(value))
135
                        if before == after:
136
                            after += " (unchanged on this version of Python)"
137
                print("""```python
138
{0}
139
#>>> Before: {1}
140
#>>> After: {2}
141
```""".format(standardise(code), before, after))
142
143
if __name__ == '__main__':
144
    main()
145