Skip to content

Commit a0f6fdd

Browse files
committed
black
1 parent e4b4119 commit a0f6fdd

File tree

4 files changed

+99
-81
lines changed

4 files changed

+99
-81
lines changed

python/asthelper.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44

55
class RaiseNameCollector(ast.NodeVisitor):
6-
76
def __init__(self):
87
self.data = set()
98
super().__init__()
@@ -13,7 +12,6 @@ def visit_Call(self, node):
1312

1413

1514
class AttributeCollector(ast.NodeVisitor):
16-
1715
def __init__(self, instance_name):
1816
self.instance_name = instance_name
1917
self.data = set()
@@ -28,14 +26,13 @@ def visit_Attribute(self, node):
2826

2927

3028
class ClassInstanceNameExtractor(ast.NodeVisitor):
31-
3229
def __init__(self):
33-
self.instance_name = 'self' # default
30+
self.instance_name = "self" # default
3431
self.set = False
3532
super().__init__()
3633

3734
def visit_FunctionDef(self, node):
38-
if node.name == '__init__':
35+
if node.name == "__init__":
3936
self.instance_name = node.args.args[0].arg
4037
self.set = True
4138
elif not self.set:
@@ -60,7 +57,7 @@ def visit_Assign(self, node):
6057

6158

6259
class MethodVisitor(ast.NodeVisitor):
63-
""" Gathers information about a method
60+
"""Gathers information about a method
6461
6562
Attributes:
6663
arguments: arguments of the method
@@ -70,6 +67,7 @@ class MethodVisitor(ast.NodeVisitor):
7067
yields: True is method yields
7168
7269
"""
70+
7371
def __init__(self, parent=True):
7472
self.parent = parent
7573
self.arguments = []
@@ -88,8 +86,10 @@ def _handle_functions(self, node):
8886
type_hint = None
8987
if arg.annotation is not None:
9088
type_hint = ast.unparse(arg.annotation)
91-
self.arguments.append({'arg': arg.arg, 'type': type_hint})
92-
if len(self.arguments) > 0 and (self.arguments[0]['arg'] == 'self' or self.arguments[0]['arg'] == 'cls'):
89+
self.arguments.append({"arg": arg.arg, "type": type_hint})
90+
if len(self.arguments) > 0 and (
91+
self.arguments[0]["arg"] == "self" or self.arguments[0]["arg"] == "cls"
92+
):
9393
self.arguments.pop(0)
9494

9595
self.returns = new_visitor.returns

python/pydocstring.py

+72-53
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,19 @@
1313

1414

1515
class InvalidSyntax(Exception):
16-
""" Raise when the syntax of processed object is invalid. """
16+
"""Raise when the syntax of processed object is invalid."""
17+
1718
pass
1819

1920

2021
class DocstringUnavailable(Exception):
21-
""" Raise when trying to process object to which there is no docstring. """
22+
"""Raise when trying to process object to which there is no docstring."""
23+
2224
pass
2325

2426

2527
class Templater:
26-
""" Class used to template the docstrings
28+
"""Class used to template the docstrings
2729
2830
Attributes:
2931
indent: used indentation
@@ -33,36 +35,54 @@ class Templater:
3335
3436
"""
3537

36-
def __init__(self, location, indent, style='google'):
38+
def __init__(self, location, indent, style="google"):
3739
self.style = style
3840
self.indent = indent
3941
self.location = location
4042

4143
def _docstring_helper(self, obj_indent, docstring):
4244
lines = []
43-
for line in docstring.split('\n'):
44-
if re.match('.', line):
45+
for line in docstring.split("\n"):
46+
if re.match(".", line):
4547
line = concat_(obj_indent, self.indent, line)
4648
lines.append(line)
4749

48-
return '\n'.join(lines)
49-
50-
def get_method_docstring(self, method_indent, args, returns, yields, raises, print_hints=False):
51-
with open(os.path.join(self.location, '..', 'styles/{}-{}.txt'.format(self.style, 'method')), 'r') as f:
50+
return "\n".join(lines)
51+
52+
def get_method_docstring(
53+
self, method_indent, args, returns, yields, raises, print_hints=False
54+
):
55+
with open(
56+
os.path.join(
57+
self.location, "..", "styles/{}-{}.txt".format(self.style, "method")
58+
),
59+
"r",
60+
) as f:
5261
self.template = ibis.Template(f.read())
53-
docstring = self.template.render(indent=self.indent, args=args, hints=print_hints,
54-
raises=raises, returns=returns, yields=yields)
62+
docstring = self.template.render(
63+
indent=self.indent,
64+
args=args,
65+
hints=print_hints,
66+
raises=raises,
67+
returns=returns,
68+
yields=yields,
69+
)
5570
return self._docstring_helper(method_indent, docstring)
5671

5772
def get_class_docstring(self, class_indent, attr):
58-
with open(os.path.join(self.location, '..', 'styles/{}-{}.txt'.format(self.style, 'class')), 'r') as f:
73+
with open(
74+
os.path.join(
75+
self.location, "..", "styles/{}-{}.txt".format(self.style, "class")
76+
),
77+
"r",
78+
) as f:
5979
self.template = ibis.Template(f.read())
6080
docstring = self.template.render(indent=self.indent, attr=attr)
6181
return self._docstring_helper(class_indent, docstring)
6282

6383

6484
class ObjectWithDocstring(abc.ABC):
65-
""" Represents an object (class, method) with the enviroment in which it is opened
85+
"""Represents an object (class, method) with the enviroment in which it is opened
6686
6787
Attributes:
6888
env: enviroment class
@@ -78,7 +98,7 @@ def __init__(self, env, templater):
7898

7999
@abc.abstractmethod
80100
def write_docstring(self, *args, **kwargs):
81-
""" Method to create a docstring for appropriate object
101+
"""Method to create a docstring for appropriate object
82102
83103
Writes the docstring to correct lines in `self.env` object.
84104
"""
@@ -88,27 +108,27 @@ def _get_sig(self):
88108
lines = []
89109
lines_it = self.env.lines_following_cursor()
90110
sig_line, first_line = next(lines_it)
91-
indent = re.findall(r'^(\s*)', first_line)[0]
111+
indent = re.findall(r"^(\s*)", first_line)[0]
92112

93113
lines.append(first_line)
94114

95-
while not self._is_valid(''.join(lines)):
115+
while not self._is_valid("".join(lines)):
96116
try:
97117
sig_line, line = next(lines_it)
98118
except StopIteration as e:
99-
raise InvalidSyntax('Object does not have valid syntax')
119+
raise InvalidSyntax("Object does not have valid syntax")
100120
lines.append(line)
101121
return sig_line, indent
102122

103123
def _object_tree(self):
104-
""" Get the source code of the object under cursor. """
124+
"""Get the source code of the object under cursor."""
105125
lines = []
106126
lines_it = self.env.lines_following_cursor()
107127
sig_line, first_line = next(lines_it)
108128

109129
lines.append(first_line)
110130

111-
obj_indent = re.findall(r'^(\s*)', first_line)[0]
131+
obj_indent = re.findall(r"^(\s*)", first_line)[0]
112132
expected_indent = concat_(obj_indent, self.env.python_indent)
113133

114134
valid_sig, _ = self._is_valid(first_line)
@@ -119,69 +139,70 @@ def _object_tree(self):
119139
except Exception as e:
120140
break
121141

122-
if valid_sig and not self._is_correct_indent(lines[-1], line, expected_indent):
142+
if valid_sig and not self._is_correct_indent(
143+
lines[-1], line, expected_indent
144+
):
123145
break
124146

125147
lines.append(line)
126148
if not valid_sig:
127-
data = ''.join(lines)
149+
data = "".join(lines)
128150
valid_sig, _ = self._is_valid(data)
129151
sig_line = last_row
130152

131153
# remove obj_indent from the beginning of all lines
132-
lines = [re.sub('^'+obj_indent, '', l) for l in lines]
154+
lines = [re.sub("^" + obj_indent, "", l) for l in lines]
133155
for i, l in enumerate(reversed(lines)):
134-
if l.strip() == '':
156+
if l.strip() == "":
135157
lines.pop()
136158
else:
137159
break
138160
if len(lines) == 1:
139-
lines.append(f'{self.env.python_indent}pass')
161+
lines.append(f"{self.env.python_indent}pass")
140162

141-
data = '\n'.join(lines)
163+
data = "\n".join(lines)
142164
try:
143165
tree = ast.parse(data)
144166
except Exception as e:
145-
raise InvalidSyntax('Object has invalid syntax.')
167+
raise InvalidSyntax("Object has invalid syntax.")
146168

147169
return sig_line, obj_indent, tree
148170

149171
def _is_correct_indent(self, previous_line, line, expected_indent):
150-
""" Check whether given line has either given indentation (or more)
151-
or does contain only nothing or whitespaces.
172+
"""Check whether given line has either given indentation (or more)
173+
or does contain only nothing or whitespaces.
152174
"""
153175
# Disclaimer: I know this does not check for multiline comments and strings
154176
# strings ''' <newline> ...<newline>..''' are a problem !!!
155-
if re.match('^'+expected_indent, line):
177+
if re.match("^" + expected_indent, line):
156178
return True
157-
elif re.match('^\s*#', line):
179+
elif re.match("^\s*#", line):
158180
return True
159-
elif re.match('^\s*["\']{3}', line):
181+
elif re.match("^\s*[\"']{3}", line):
160182
return True
161-
elif re.match('.*\\$', previous_line):
183+
elif re.match(".*\\$", previous_line):
162184
return True
163-
elif re.match('^\s*$', line):
185+
elif re.match("^\s*$", line):
164186
return True
165187

166188
return False
167189

168190
def _is_valid(self, lines):
169-
func = concat_(lines.lstrip(), '\n pass')
191+
func = concat_(lines.lstrip(), "\n pass")
170192
try:
171193
tree = ast.parse(func)
172194
return True, tree
173195
except SyntaxError as e:
174196
return False, None
175197

176198
def write_simple_docstring(self):
177-
""" Writes the generated docstring in the enviroment """
199+
"""Writes the generated docstring in the enviroment"""
178200
sig_line, indent = self._get_sig()
179201
docstring = concat_(indent, self.templater.indent, '""" """')
180202
self.env.append_after_line(sig_line, docstring)
181203

182204

183205
class MethodController(ObjectWithDocstring):
184-
185206
def __init__(self, env, templater):
186207
super().__init__(env, templater)
187208

@@ -197,12 +218,12 @@ def write_docstring(self, print_hints=False):
197218
sig_line, method_indent, tree = self._object_tree()
198219
args, returns, yields, raises = self._process_tree(tree)
199220
docstring = self.templater.get_method_docstring(
200-
method_indent, args, returns, yields, raises, print_hints)
221+
method_indent, args, returns, yields, raises, print_hints
222+
)
201223
self.env.append_after_line(sig_line, docstring)
202224

203225

204226
class ClassController(ObjectWithDocstring):
205-
206227
def __init__(self, env, templater):
207228
super().__init__(env, templater)
208229

@@ -222,7 +243,7 @@ def write_docstring(self, *args, **kwargs):
222243

223244

224245
class Docstring:
225-
""" Class used by user to generate docstrings"""
246+
"""Class used by user to generate docstrings"""
226247

227248
def __init__(self):
228249
env = VimEnviroment()
@@ -235,32 +256,30 @@ def __init__(self):
235256

236257
def _controller_factory(self, env, templater):
237258
line = env.current_line
238-
first_word = re.match(r'^\s*(\w+).*', line).groups()[0]
239-
if first_word == 'def':
259+
first_word = re.match(r"^\s*(\w+).*", line).groups()[0]
260+
if first_word == "def":
240261
return MethodController(env, templater)
241-
elif first_word == 'class':
262+
elif first_word == "class":
242263
return ClassController(env, templater)
243-
elif first_word == 'async':
244-
second_word_catch = re.match(r'^\s*\w+\s+(\w+).*', line)
264+
elif first_word == "async":
265+
second_word_catch = re.match(r"^\s*\w+\s+(\w+).*", line)
245266
if second_word_catch:
246267
second_word = second_word_catch.groups()[0]
247-
if second_word == 'def':
268+
if second_word == "def":
248269
return MethodController(env, templater)
249270

250-
raise DocstringUnavailable(
251-
'Docstring cannot be created for selected object')
271+
raise DocstringUnavailable("Docstring cannot be created for selected object")
252272

253273
def full_docstring(self, print_hints=False):
254-
""" Writes docstring containing arguments, returns, raises, ... """
274+
"""Writes docstring containing arguments, returns, raises, ..."""
255275
try:
256276
self.obj_controller.write_docstring(print_hints=print_hints)
257277
except Exception as e:
258-
print(concat_('Doctring ERROR: ', e))
278+
print(concat_("Doctring ERROR: ", e))
259279

260280
def oneline_docstring(self):
261-
""" Writes only a one-line empty docstring """
281+
"""Writes only a one-line empty docstring"""
262282
try:
263283
self.obj_controller.write_simple_docstring()
264284
except Exception as e:
265-
print(concat_('Doctring ERROR: ', e))
266-
285+
print(concat_("Doctring ERROR: ", e))

python/utils.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
def concat_(*args):
2-
""" Converts `args` into string and joines them """
3-
return ''.join([str(x) for x in list(args)])
2+
"""Converts `args` into string and joines them"""
3+
return "".join([str(x) for x in list(args)])

0 commit comments

Comments
 (0)