7
7
8
8
import logging
9
9
from collections .abc import Mapping
10
+ from types import ModuleType
10
11
from typing import Any
11
12
from warnings import warn
12
13
@@ -266,6 +267,7 @@ def eval(
266
267
self ,
267
268
expr : str ,
268
269
parameters : Mapping [str , str ] | None = None ,
270
+ modules : Mapping [str , ModuleType ] | None = None ,
269
271
) -> LGDO :
270
272
"""Apply column operations to the table and return a new LGDO.
271
273
@@ -299,6 +301,10 @@ def eval(
299
301
a dictionary of function parameters. Passed to
300
302
:func:`numexpr.evaluate`` as `local_dict` argument or to
301
303
:func:`eval` as `locals` argument.
304
+ modules
305
+ a dictionary of additional modules used by the expression. If this is not `None`
306
+ then :func:`eval`is used and the expression can depend on any modules from this dictionary in
307
+ addition to awkward and numpy. These are passed to :func:`eval` as `globals` argument.
302
308
303
309
Examples
304
310
--------
@@ -339,8 +345,8 @@ def eval(
339
345
msg = f"evaluating { expr !r} with locals={ (self_unwrap | parameters )} and { has_ak = } "
340
346
log .debug (msg )
341
347
342
- # use numexpr if we are only dealing with numpy data types
343
- if not has_ak :
348
+ # use numexpr if we are only dealing with numpy data types (and no global dictionary)
349
+ if not has_ak and modules is None :
344
350
out_data = ne .evaluate (
345
351
expr ,
346
352
local_dict = (self_unwrap | parameters ),
@@ -366,6 +372,9 @@ def eval(
366
372
367
373
# resort to good ol' eval()
368
374
globs = {"ak" : ak , "np" : np }
375
+ if modules is not None :
376
+ globs = globs | modules
377
+
369
378
out_data = eval (expr , globs , (self_unwrap | parameters ))
370
379
371
380
msg = f"...the result is { out_data !r} "
@@ -380,6 +389,10 @@ def eval(
380
389
if np .isscalar (out_data ):
381
390
return Scalar (out_data )
382
391
392
+ # if out_data is already an LGDO just return it
393
+ if isinstance (out_data , LGDO ):
394
+ return out_data
395
+
383
396
msg = (
384
397
f"evaluation resulted in a { type (out_data )} object, "
385
398
"I don't know which LGDO this corresponds to"
0 commit comments