Skip to content

Commit 2ca3455

Browse files
vepadulanodpiparo
authored andcommitted
[python] Lint and format
1 parent cb97b80 commit 2ca3455

File tree

1 file changed

+67
-54
lines changed
  • bindings/pyroot/pythonizations/python/ROOT/_pythonization

1 file changed

+67
-54
lines changed

bindings/pyroot/pythonizations/python/ROOT/_pythonization/__init__.py

+67-54
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,22 @@
77
# For the licensing terms see $ROOTSYS/LICENSE. #
88
# For the list of contributors see $ROOTSYS/README/CREDITS. #
99
################################################################################
10-
1110
import importlib
1211
import inspect
1312
import pkgutil
14-
import re
15-
import sys
1613
import traceback
1714

1815
import cppyy
16+
17+
from ._generic import pythonize_generic
18+
1919
# \cond INTERNALS
2020
gbl_namespace = cppyy.gbl
2121
# \endcond
2222

23-
from ._generic import pythonize_generic
2423

25-
26-
def pythonization(class_name, ns='::', is_prefix=False):
27-
r'''
24+
def pythonization(class_name, ns="::", is_prefix=False):
25+
r"""
2826
\ingroup Pythonizations
2927
Decorator that allows to pythonize C++ classes. To pythonize means to add
3028
some extra behaviour to a C++ class that is used from Python via PyROOT,
@@ -56,28 +54,29 @@ def pythonization(class_name, ns='::', is_prefix=False):
5654
function: function that receives the user-defined function and
5755
decorates it.
5856
59-
'''
57+
"""
6058

6159
# Type check and parsing of target argument.
6260
# Retrieve the scope(s) of the class(es)/prefix(es) to register the
6361
# pythonizor in the right scope(s)
6462
target = _check_target(class_name)
6563

6664
# Remove trailing '::' from namespace
67-
if ns.endswith('::'):
65+
if ns.endswith("::"):
6866
ns = ns[:-2]
6967

7068
# Create a filter lambda for the target class(es)/prefix(es)
7169
if is_prefix:
70+
7271
def passes_filter(class_name):
73-
return any(class_name.startswith(prefix)
74-
for prefix in target)
72+
return any(class_name.startswith(prefix) for prefix in target)
7573
else:
74+
7675
def passes_filter(class_name):
7776
return class_name in target
7877

7978
def pythonization_impl(user_pythonizor):
80-
'''
79+
"""
8180
The real decorator. Accepts a user-provided function and decorates it.
8281
An inner function - a wrapper of the user function - is registered in
8382
cppyy as a pythonizor.
@@ -93,7 +92,7 @@ def pythonization_impl(user_pythonizor):
9392
Returns:
9493
function: the user function, after being registered as a
9594
pythonizor.
96-
'''
95+
"""
9796

9897
npars = _check_num_pars(user_pythonizor)
9998

@@ -103,7 +102,7 @@ def pythonization_impl(user_pythonizor):
103102
_find_used_classes(ns, passes_filter, user_pythonizor, npars)
104103

105104
def cppyy_pythonizor(klass, name):
106-
'''
105+
"""
107106
Wrapper function with the parameters that cppyy requires for a
108107
pythonizor function (class proxy and class name). It invokes the
109108
user function only if the current class - a candidate for being
@@ -114,7 +113,7 @@ def cppyy_pythonizor(klass, name):
114113
current candidate to be pythonized.
115114
name (string): name of the class that is the current candidate
116115
to be pythonized.
117-
'''
116+
"""
118117

119118
fqn = klass.__cpp_name__
120119

@@ -136,10 +135,12 @@ def cppyy_pythonizor(klass, name):
136135

137136
return pythonization_impl
138137

138+
139139
# \cond INTERNALS
140140

141+
141142
def _check_target(target):
142-
'''
143+
"""
143144
Helper function to check the type of the `class name` argument specified by
144145
the user in a @pythonization decorator.
145146
@@ -148,83 +149,90 @@ def _check_target(target):
148149
149150
Returns:
150151
list[string]: class name(s)/prefix(es) in `target`, with no repetitions.
151-
'''
152+
"""
152153

153154
if isinstance(target, str):
154155
_check_no_namespace(target)
155-
target = [ target ]
156+
target = [target]
156157
else:
157158
for name in target:
158159
if isinstance(name, str):
159160
_check_no_namespace(name)
160161
else:
161-
raise TypeError('Invalid type of "target" argument in '
162-
'@pythonization: must be string or iterable of '
163-
'strings')
162+
raise TypeError(
163+
'Invalid type of "target" argument in @pythonization: must be string or iterable of strings'
164+
)
164165
# Remove possible duplicates
165166
target = list(set(target))
166167

167168
return target
168169

170+
169171
def _check_no_namespace(target):
170-
'''
172+
"""
171173
Checks that a given target of a pythonizor does not specify a namespace
172174
(only the class name / prefix of a class name should be present).
173175
174176
Args:
175177
target (string): class name/prefix.
176-
'''
178+
"""
179+
180+
if target.find("::") >= 0:
181+
raise ValueError(
182+
'Invalid value of "class_name" argument in '
183+
'@pythonization: namespace definition found ("{}"). '
184+
'Please use the "ns" parameter to specify the '
185+
"namespace".format(target)
186+
)
177187

178-
if target.find('::') >= 0:
179-
raise ValueError('Invalid value of "class_name" argument in '
180-
'@pythonization: namespace definition found ("{}"). '
181-
'Please use the "ns" parameter to specify the '
182-
'namespace'.format(target))
183188

184189
def _check_num_pars(f):
185-
'''
190+
"""
186191
Checks the number of parameters of the `f` function.
187192
188193
Args:
189194
f (function): user pythonizor function.
190195
191196
Returns:
192197
int: number of positional parameters of `f`.
193-
'''
198+
"""
194199
npars = len(inspect.getfullargspec(f).args)
195200
if npars == 0 or npars > 2:
196-
raise TypeError('Pythonizor function {} has a wrong number of '
197-
'parameters ({}). Allowed parameters are the class to '
198-
'be pythonized and (optionally) its name.'
199-
.format(f.__name__, npars))
201+
raise TypeError(
202+
"Pythonizor function {} has a wrong number of "
203+
"parameters ({}). Allowed parameters are the class to "
204+
"be pythonized and (optionally) its name.".format(f.__name__, npars)
205+
)
200206

201207
return npars
202208

209+
203210
def _invoke(user_pythonizor, npars, klass, fqn):
204-
'''
211+
"""
205212
Invokes the given user pythonizor function with the right arguments.
206213
207214
Args:
208215
user_pythonizor (function): user pythonizor function.
209216
npars (int): number of parameters of the user pythonizor function.
210217
klass (class type): cppyy proxy of the class to be pythonized.
211218
fqn (string): fully-qualified name of the class to be pythonized.
212-
'''
219+
"""
213220

214221
try:
215222
if npars == 1:
216223
user_pythonizor(klass)
217224
else:
218225
user_pythonizor(klass, fqn)
219-
except Exception as e:
220-
print('Error pythonizing class {}:'.format(fqn))
226+
except Exception:
227+
print("Error pythonizing class {}:".format(fqn))
221228
traceback.print_exc()
222229
# Propagate the error so that the class lookup that triggered this
223230
# pythonization fails too and the application stops
224231
raise RuntimeError
225232

233+
226234
def _find_used_classes(ns, passes_filter, user_pythonizor, npars):
227-
'''
235+
"""
228236
Finds already instantiated classes in namespace `ns` that pass the filter
229237
of `passes_filter`. Every matching class is pythonized with the
230238
`user_pythonizor` function.
@@ -237,7 +245,7 @@ def _find_used_classes(ns, passes_filter, user_pythonizor, npars):
237245
is the target of `user_pythonizor`.
238246
user_pythonizor (function): user pythonizor function.
239247
npars (int): number of parameters of the user pythonizor function.
240-
'''
248+
"""
241249

242250
ns_obj = _find_namespace(ns)
243251
if ns_obj is None:
@@ -266,15 +274,16 @@ def get_class_name(instantiation):
266274
return instantiation.__name__
267275

268276
raise RuntimeError(
269-
f"The template instantiation '{instantiation}' cannot be properly pythonized. Please report this as a bug.")
277+
f"The template instantiation '{instantiation}' cannot be properly pythonized. Please report this as a bug."
278+
)
270279

271280
ns_vars = vars(ns_obj)
272281
for var_name, var_value in ns_vars.items():
273-
if str(var_value).startswith('<class cppyy.gbl.'):
282+
if str(var_value).startswith("<class cppyy.gbl."):
274283
# It's a class proxy
275284
pythonize_if_match(var_name, var_value)
276285

277-
if str(var_value).startswith('<cppyy.Template'):
286+
if str(var_value).startswith("<cppyy.Template"):
278287
# If this is a template, pythonize the instances. Note that in
279288
# older cppyy, template instantiations are cached by
280289
# fully-qualified name directly in the namespace, so they are
@@ -284,12 +293,13 @@ def get_class_name(instantiation):
284293
# Make sure we don't do any redundant pythonization, e.g. if we
285294
# use a version of cppyy that caches both in the namespace and
286295
# in the _instantiations attribute.
287-
if not instance in ns_vars:
296+
if instance not in ns_vars:
288297
instance_name = var_name + "<" + ",".join(map(get_class_name, args)) + ">"
289298
pythonize_if_match(instance_name, instance)
290299

300+
291301
def _find_namespace(ns):
292-
'''
302+
"""
293303
Finds and returns the proxy object of the `ns` namespace, if it has already
294304
been accessed.
295305
@@ -299,29 +309,32 @@ def _find_namespace(ns):
299309
Returns:
300310
namespace proxy object, if the namespace has already been accessed,
301311
otherwise None.
302-
'''
312+
"""
303313

304-
if ns == '':
314+
if ns == "":
305315
return gbl_namespace
306316

307317
ns_obj = gbl_namespace
308318
# Get all namespaces in a list
309-
every_ns = ns.split('::')
319+
every_ns = ns.split("::")
310320
for ns in every_ns:
311321
ns_vars = vars(ns_obj)
312-
if not ns in ns_vars:
322+
if ns not in ns_vars:
313323
return None
314324
ns_obj = getattr(ns_obj, ns)
315325

316326
return ns_obj
317327

328+
318329
def _register_pythonizations():
319-
'''
330+
"""
320331
Registers the ROOT pythonizations with cppyy for lazy injection.
321-
'''
332+
"""
322333

323-
exclude = [ '_rdf_utils', '_rdf_pyz', '_rdf_conversion_maps' ]
324-
for _, module_name, _ in pkgutil.walk_packages(__path__):
334+
exclude = ["_rdf_utils", "_rdf_pyz", "_rdf_conversion_maps"]
335+
for _, module_name, _ in pkgutil.walk_packages(__path__):
325336
if module_name not in exclude:
326-
importlib.import_module(__name__ + '.' + module_name)
337+
importlib.import_module(__name__ + "." + module_name)
338+
339+
327340
# \endcond

0 commit comments

Comments
 (0)