Conditions | 19 |
Total Lines | 52 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 0 |
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:
If many parameters/temporary variables are present:
Complex classes like which() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
1 | # -*- coding: utf-8 -*- |
||
35 | def which(filename, interactive=False, verbose=False): |
||
36 | """Yield all executable files on path that matches `filename`. |
||
37 | """ |
||
38 | exe = os.environ.get('PATHEXT', ['.cmd', '.bat', '.exe', '.com']) |
||
39 | |||
40 | name, ext = os.path.splitext(filename) |
||
41 | if ext and (ext in exe): # pragma: nocover |
||
42 | exe = [] |
||
43 | |||
44 | def match(filenames): |
||
45 | res = set() |
||
46 | for fname in filenames: |
||
47 | if fname == filename: # pragma: nocover |
||
48 | res.add(fname) |
||
49 | continue |
||
50 | |||
51 | fn_name, fn_ext = os.path.splitext(fname) |
||
52 | if name == fn_name: |
||
53 | for suffix in exe: |
||
54 | if name + fn_ext == fname: |
||
55 | res.add(fname) |
||
56 | |||
57 | return sorted(res) |
||
58 | |||
59 | returnset = set() |
||
60 | found = False |
||
61 | for pth in get_path_directories(): |
||
62 | if not pth.strip(): # pragma: nocover |
||
63 | continue |
||
64 | |||
65 | if verbose: # pragma: nocover |
||
66 | print('checking pth..') |
||
67 | |||
68 | try: |
||
69 | fnames = os.listdir(pth) |
||
70 | except: # pragma: nocover |
||
71 | continue |
||
72 | |||
73 | matched = match(fnames) |
||
74 | |||
75 | if matched: |
||
76 | for m in matched: |
||
77 | found_file = os.path.normcase(os.path.normpath(os.path.join(pth, m))) |
||
78 | if found_file not in returnset: |
||
79 | if is_executable(found_file): |
||
80 | yield found_file |
||
81 | returnset.add(found_file) |
||
82 | found = True |
||
83 | |||
84 | if not found and interactive: # pragma: nocover |
||
85 | print("Couldn't find %r anywhere on the path.." % filename) |
||
86 | sys.exit(1) |
||
87 | |||
93 |