1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
|
#!/usr/bin/env python3
# --------------------( LICENSE )--------------------
# Copyright (c) 2014-2025 Beartype authors.
# See "LICENSE" for further details.
'''
Project-wide **callable source code** (i.e., file providing the uncompiled
pure-Python source code from which a compiled callable originated) utilities.
This private submodule implements supplementary callable-specific utility
functions required by various :mod:`beartype` facilities, including callables
generated by the :func:`beartype.beartype` decorator.
This private submodule is *not* intended for importation by downstream callers.
'''
# ....................{ TODO }....................
#FIXME: *FILE UPSTREAM CPYTHON ISSUES.* Unfortunately, this submodule exposed a
#number of significant issues in the CPython stdlib -- all concerning parsing
#of lambda functions. These include:
#
#1. The inspect.getsourcelines() function raises unexpected
# "tokenize.TokenError" exceptions when passed lambda functions preceded by
# one or more triple-quoted strings: e.g.,
# >>> import inspect
# >>> built_to_fail = (
# ... ('''Uh-oh.
# ... ''', lambda obj: 'Oh, Gods above and/or below!'
# ... )
# ... )
# >>> inspect.getsourcelines(built_to_fail[1])}
# tokenize.TokenError: ('EOF in multi-line string', (323, 8))
#2. The "func.__code__.co_firstlineno" attribute is incorrect for syntactic
# constructs resembling:
# assert is_hint_pep593_beartype(Annotated[ # <--- line 1
# str, Is[lambda text: bool(text)]]) is True # <--- line 2
# Given such a construct, the nested lambda function should have a
# "func.__code__.co_firstlineno" attribute whose value is "2". Instead, that
# attribute's value is "1". This then complicates detection of lambda
# functions, which are already non-trivial enough to detect. Specifically,
# this causes the inspect.findsource() function to either raise an unexpected
# "OSError" *OR* return incorrect source when passed a file containing the
# above snippet. In either case, that is bad. *sigh*
#3. Introspecting the source code for two or more lambdas defined on the same
# line is infeasible, because code objects only record line numbers rather
# than both line and column numbers. Well, that's unfortunate.
# ^--- Actually, we're *PRETTY* sure that Python 3.11 has finally resolved
# this by now recording column numbers with code objects. So, let's
# improve the logic below to handle this edge case under Python >= 3.11.
#FIXME: Contribute get_func_code_or_none() back to this StackOverflow question
#as a new answer, as this is highly non-trivial, frankly:
# https://stackoverflow.com/questions/59498679/how-can-i-get-exactly-the-code-of-a-lambda-function-in-python/64421174#64421174
# ....................{ IMPORTS }....................
from ast import (
NodeVisitor,
parse as ast_parse,
unparse as ast_unparse,
)
from beartype.roar._roarwarn import _BeartypeUtilCallableWarning
from beartype.typing import (
List,
Optional,
)
from beartype._data.typing.datatyping import TypeWarning
from beartype._util.error.utilerrwarn import issue_warning
from beartype._util.func.utilfunccodeobj import get_func_codeobj
from collections.abc import Callable
from inspect import (
findsource,
getsource,
)
from traceback import format_exc
# ....................{ GETTERS ~ code : lines }....................
#FIXME: Unit test us up.
def get_func_code_lines_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
'''
**Line-oriented callable source code** (i.e., string concatenating the
subset of all lines of the on-disk Python script or module declaring the
passed pure-Python callable) if that callable was declared on-disk *or*
:data:`None` otherwise (i.e., if that callable was dynamically declared
in-memory).
Caveats
-------
**The higher-level** :func:`get_func_code_or_none` **getter should typically
be called instead.** Why? Because this lower-level getter inexactly returns
all lines embedding the declaration of the passed callable rather than the
exact substring of those lines declaring that callable. Although typically
identical for non-lambda functions, those two strings typically differ for
lambda functions. Lambda functions are expressions embedded in larger
statements rather than full statements.
**This getter is excruciatingly slow.** See the
:func:`.get_func_code_or_none` getter for further commentary.
Parameters
----------
func : Callable
Callable to be inspected.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error.
Defaults to :exc:`._BeartypeUtilCallableWarning`.
Returns
-------
Optional[str]
Either:
* If the passed callable was physically declared by a file, a string
concatenating the subset of lines of that file declaring that
callable.
* If the passed callable was dynamically declared in-memory,
:data:`None`.
Warns
-----
warning_cls
If the passed callable is defined by a pure-Python source code file but
is *not* parsable from that file. While we could allow any parser
exception to percolate up the call stack and halt the active Python
process when left unhandled, doing so would render :mod:`beartype`
fragile -- gaining us little and costing us much.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfuncfile import is_func_file
from beartype._util.text.utiltextlabel import label_callable
# If the passed callable exists on-disk and is thus pure-Python...
if is_func_file(func):
# Attempt to defer to the standard inspect.getsource() function.
try:
return getsource(func)
# If that function raised *ANY* exception, reduce that exception to a
# non-fatal warning.
except Exception:
# Reduce this fatal error to a non-fatal warning embedding a full
# exception traceback as a formatted string.
issue_warning(
cls=warning_cls,
message=f'{label_callable(func)} not parsable:\n{format_exc()}',
)
# Else, the passed callable only exists in-memory.
# Return "None" as a fallback.
return None
#FIXME: Unit test us up.
def get_func_file_code_lines_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
'''
**Line-oriented callable source file code** (i.e., string concatenating
*all* lines of the on-disk Python script or module declaring the passed
pure-Python callable) if that callable was declared on-disk *or*:
:data:`None` otherwise (i.e., if that callable was dynamically declared
in-memory).
Caveats
-------
**This getter is excruciatingly slow.** See the
:func:`.get_func_code_or_none` getter for further commentary.
Parameters
----------
func : Callable
Callable to be inspected.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error.
Defaults to :exc:`._BeartypeUtilCallableWarning`.
Returns
-------
Optional[str]
Either:
* If the passed callable was physically declared by an file, a string
concatenating *all* lines of that file.
* If the passed callable was dynamically declared in-memory,
:data:`None`.
Warns
-----
:class:`warning_cls`
If the passed callable is defined by a pure-Python source code file
but is *not* parsable from that file. While we could allow any parser
exception to percolate up the call stack and halt the active Python
process when left unhandled, doing so would render :mod:`beartype`
fragile -- gaining us little and costing us much.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfuncfile import is_func_file
from beartype._util.text.utiltextlabel import label_callable
# If the passed callable exists on-disk and is thus pure-Python...
if is_func_file(func):
# Attempt to defer to the standard inspect.findsource() function, which
# returns a 2-tuple "(file_code_lines, file_code_lineno_start)", where:
# * "file_code_lines" is a list of all lines of the script or module
# declaring the passed callable.
# * "file_code_lineno_start" is the line number of the first such line
# declaring the passed callable. Since this line number is already
# provided by the "co_firstlineno" instance variable of this
# callable's code object, however, there is *NO* reason whatsoever to
# return this line number. Indeed, it's unclear why that function
# returns this uselessly redundant metadata in the first place.
try:
# List of all lines of the file declaring the passed callable.
func_file_code_lines, _ = findsource(func)
# Return this list concatenated into a string.
return ''.join(func_file_code_lines)
# If that function raised *ANY* exception, reduce that exception to a
# non-fatal warning. While we could permit this exception to percolate
# up the call stack and inevitably halt the active Python process when
# left unhandled, doing so would render @beartype fragile -- gaining us
# little and costing us much.
#
# Notably, the lower-level inspect.getblock() function internally
# called by the higher-level findsource() function prematurely halted
# due to an unexpected bug in the pure-Python tokenizer leveraged by
# inspect.getblock(). Notably, this occurs when passing lambda
# functions preceded by triple-quoted strings: e.g.,
# >>> import inspect
# >>> built_to_fail = (
# ... ('''Uh-oh.
# ... ''', lambda obj: 'Oh, Gods above and/or below!'
# ... )
# ... )
# >>> inspect.findsource(built_to_fail[1])}
# tokenize.TokenError: ('EOF in multi-line string', (323, 8))
except Exception:
# Reduce this fatal error to a non-fatal warning embedding a full
# exception traceback as a formatted string.
issue_warning(
cls=warning_cls,
message=f'{label_callable(func)} not parsable:\n{format_exc()}',
)
# Else, the passed callable only exists in-memory.
# Return "None" as a fallback.
return None
# ....................{ GETTERS ~ code : lambda }....................
def get_func_code_or_none(
# Mandatory parameters.
func: Callable,
# Optional parameters.
warning_cls: TypeWarning = _BeartypeUtilCallableWarning,
) -> Optional[str]:
'''
**Callable source code** (i.e., substring of all lines of the on-disk Python
script or module declaring the passed pure-Python callable) if that callable
was declared on-disk *or* :data:`None` otherwise (i.e., if that callable was
dynamically declared in-memory).
Specifically, this getter returns:
* If the passed callable is a lambda function, the exact substring of that
code declaring that lambda function.
* Else, the concatenation of all lines of that code declaring that callable.
Caveats
-------
**This getter is excruciatingly slow.** This getter should *only* be called
when unavoidable and ideally *only* in performance-agnostic code paths.
Notably, this getter finds relevant lines by parsing the script or module
declaring the passed callable starting at the first line of that declaration
and continuing until a rudimentary tokenizer implemented in pure-Python
(with *no* concern for optimization and thus slow beyond all understanding
of slow) detects the last line of that declaration. In theory, we could
significantly optimize that routine; in practice, anyone who cares will
preferably compile or JIT :mod:`beartype` instead.
Parameters
----------
func : Callable
Callable to be inspected.
warning_cls : TypeWarning, optional
Type of warning to be emitted in the event of a non-fatal error.
Defaults to :exc:`._BeartypeUtilCallableWarning`.
Returns
-------
Optional[str]
Either:
* If the passed callable was physically declared by a file, the exact
substring of all lines of that file declaring that callable.
* If the passed callable was dynamically declared in-memory,
:data:`None`.
Warns
-----
warning_cls
If the passed callable is a pure-Python lambda function that was
physically declared by either:
* A large file exceeding a sane maximum file size (e.g., 1MB). Note
that:
* If this is *not* explicitly guarded against, passing absurdly long
strings to the :func:`ast.parse` function can actually induce a
segmentation fault in the active Python process. This is a
`longstanding and unresolved issue <ast issue_>`__ in the :mod:`ast`
module.
* Generously assuming each line of that file contains between
40 to 80 characters, this maximum supports files of between 12,500
to 25,000 lines, which at even the lower end of that range covers
most real-world files of interest.
* A complex (but *not* necessarily large) file causing the recursive
:func:`ast.parse` or :func:`ast.unparse` function or any other
:mod:`ast` callable to exceed Python's recursion limit by exhausting
the stack.
* A line of source code declaring two or more lambda functions (e.g.,
``lambdas = lambda: 'and black,', lambda: 'and pale,'``). In this
case, the substring of code declaring the first such function is
ambiguously returned; all subsequent such functions are unavoidably
ignored.
.. _ast issue:
https://bugs.python.org/issue32758.
See Also
--------
https://stackoverflow.com/questions/59498679/how-can-i-get-exactly-the-code-of-a-lambda-function-in-python/64421174#64421174
StackOverflow answer strongly inspiring this implementation.
'''
# Avoid circular import dependencies.
from beartype._util.func.utilfunctest import is_func_lambda
from beartype._util.text.utiltextlabel import label_callable
# If the passed callable is a pure-Python lambda function...
if is_func_lambda(func):
# Attempt to parse the substring of the source code defining this lambda
# from the file providing that code.
#
# For safety, this function reduces *ALL* exceptions raised by this
# introspection to non-fatal warnings and returns "None". Why? Because
# the standard "ast" module in general and our "_LambdaNodeUnparser"
# class in specific are sufficiently fragile as to warrant extreme
# caution. AST parsing and unparsing is notoriously unreliable across
# different versions of different Python interpreters and compilers.
#
# Moreover, we *NEVER* call this function in a critical code path; we
# *ONLY* call this function to construct human-readable exception
# messages. Clearly, raising low-level non-human-readable exceptions
# when attempting to raise high-level human-readable exceptions rather
# defeats the entire purpose of the latter.
#
# Lastly, note that "pytest" will still fail any tests emitting
# unexpected warnings. In short, raising exceptions here would gain
# @beartype little and cost @beartype much.
try:
# String concatenating all lines of the file defining that lambda if
# that lambda is defined by a file *OR* "None" otherwise.
lambda_file_code = get_func_file_code_lines_or_none(
func=func, warning_cls=warning_cls)
# If that lambda is defined by a file...
if lambda_file_code:
# Code object underlying this lambda.
func_codeobj = get_func_codeobj(func)
# If this file exceeds a sane maximum file size, emit a
# non-fatal warning and safely ignore this file.
if len(lambda_file_code) >= _LAMBDA_CODE_FILESIZE_MAX:
issue_warning(
cls=warning_cls,
message=(
f'{label_callable(func)} not parsable, '
f'as file size exceeds safe maximum '
f'{_LAMBDA_CODE_FILESIZE_MAX}MB.'
),
)
# Else, this file *SHOULD* be safely parsable by the standard
# "ast" module without inducing a fatal segmentation fault.
else:
# Abstract syntax tree (AST) parsed from this file.
ast_tree = ast_parse(lambda_file_code)
# Lambda node unparser decompiling all AST lambda nodes
# encapsulating lambda functions starting at the same line
# number as the passed lambda in this file.
lambda_node_unparser = _LambdaNodeUnparser(
lambda_lineno=func_codeobj.co_firstlineno)
# Perform this decompilation.
lambda_node_unparser.visit(ast_tree)
# List of each code substring exactly covering each lambda
# function starting at that line number.
lambdas_code = lambda_node_unparser.lambdas_code
# If one or more lambda functions start at that line
# number...
if lambdas_code:
# If two or more lambda functions start at that line
# number, emit a non-fatal warning. Since lambda
# functions only provide a starting line number rather
# than both starting line number *AND* column, we have
# *NO* means of disambiguating between these lambda
# functions and thus *CANNOT* raise an exception.
if len(lambdas_code) >= 2:
# Human-readable concatenation of the definitions of
# all lambda functions defined on that line.
lambdas_code_str = '\n '.join(lambdas_code)
# Emit this warning.
issue_warning(
cls=warning_cls,
message=(
f'{label_callable(func)} ambiguous, '
f'as that line defines '
f'{len(lambdas_code)} lambdas; '
f'arbitrarily selecting first '
f'lambda:\n{lambdas_code_str}'
),
)
# Else, that line number defines one lambda.
# Return the substring covering that lambda.
return lambdas_code[0]
# Else, *NO* lambda functions start at that line number. In
# this case, emit a non-fatal warning.
#
# Ideally, we would instead raise a fatal exception. Why?
# Because this edge case violates expectations. Since the
# passed lambda function claims it originates from some line
# number of some file *AND* since that file both exists and
# is parsable as valid Python, we expect that line number to
# define one or more lambda functions. If it does not,
# raising an exception seems superficially reasonable. Yet,
# we don't. See above.
else:
issue_warning(
cls=warning_cls,
message=f'{label_callable(func)} not found.',
)
# Else, that lambda is dynamically defined in-memory.
# If *ANY* of the dodgy stdlib callables (e.g., ast.parse(),
# inspect.findsource()) called above raise *ANY* other unexpected
# exception, reduce this fatal error to a non-fatal warning with an
# exception traceback as a formatted string.
#
# Note that the likeliest (but certainly *NOT* only) type of exception
# to be raised is a "RecursionError", as described by the official
# documentation for the ast.unparse() function:
# Warning: Trying to unparse a highly complex expression would
# result with RecursionError.
except Exception:
issue_warning(
cls=warning_cls,
message=(
f'{label_callable(func)} not parsable:\n'
f'{format_exc()}'
),
)
# Else, the passed callable is *NOT* a pure-Python lambda function.
# In any case, the above logic failed to introspect code for the passed
# callable. Defer to the get_func_code_lines_or_none() function.
return get_func_code_lines_or_none(func=func, warning_cls=warning_cls)
# ....................{ GETTERS ~ label }....................
#FIXME: This getter no longer has a sane reason to exist. Consider excising.
# from beartype.roar._roarexc import _BeartypeUtilCallableException
# from beartype._cave._cavefast import CallableTypes
# from sys import modules
#
# def get_func_code_label(func: Callable) -> str:
# '''
# Human-readable label describing the **origin** (i.e., uncompiled source) of
# the passed callable.
#
# Specifically, this getter returns either:
#
# * If that callable is pure-Python *and* physically declared on-disk, the
# absolute filename of the uncompiled on-disk Python script or module
# physically declaring that callable.
# * If that callable is pure-Python *and* dynamically declared in-memory,
# the placeholder string ``"<string>"``.
# * If that callable is C-based, the placeholder string ``"<C-based>"``.
#
# Caveats
# ----------
# **This getter is intentionally implemented for speed rather than robustness
# against unlikely edge cases.** The string returned by this getter is *only*
# intended to be embedded in human-readable labels, warnings, and exceptions.
# Avoid using this string for *any* mission-critical purpose.
#
# Parameters
# ----------
# func : Callable
# Callable to be inspected.
#
# Returns
# ----------
# str
# Either:
#
# * If that callable is physically declared by an uncompiled Python
# script or module, the absolute filename of this script or module.
# * Else, the placeholder string ``"<string>"`` implying that callable to
# have been dynamically declared in-memory.
#
# Raises
# ------
# _BeartypeUtilCallableException
# If that callable is *not* callable.
#
# See Also
# ----------
# :func:`inspect.getsourcefile`
# Inefficient stdlib function strongly inspiring this implementation,
# which has been highly optimized for use by the performance-sensitive
# :func:`beartype.beartype` decorator.
# '''
#
# # If this callable is uncallable, raise an exception.
# if not callable(func):
# raise _BeartypeUtilCallableException(f'{repr(func)} not callable.')
# # Else, this callable is callable.
#
# # Human-readable label describing the origin of the passed callable.
# func_origin_label = '<string>'
#
# # If this callable is a standard callable rather than arbitrary class or
# # object overriding the __call__() dunder method...
# if isinstance(func, CallableTypes):
# # Avoid circular import dependencies.
# from beartype._util.func.utilfuncfile import get_func_filename_or_none
# from beartype._util.func.utilfuncwrap import unwrap_func_all_isomorphic
#
# # Code object underlying the passed pure-Python callable unwrapped if
# # this callable is pure-Python *OR* "None" otherwise.
# func_filename = get_func_filename_or_none(unwrap_func_all_isomorphic(func))
#
# # If this callable has a code object, set this label to either the
# # absolute filename of the physical Python module or script declaring
# # this callable if this code object provides that metadata *OR* a
# # placeholder string specific to C-based callables otherwise.
# func_origin_label = func_filename if func_filename else '<C-based>'
# # Else, this callable is *NOT* a standard callable. In this case...
# else:
# # If this callable is *NOT* a class (i.e., is an object defining the
# # __call__() method), reduce this callable to the class of this object.
# if not isinstance(func, type):
# func = type(func)
# # In either case, this callable is now a class.
#
# # Fully-qualified name of the module declaring this class if this class
# # was physically declared by an on-disk module *OR* "None" otherwise.
# func_module_name = func.__module__
#
# # If this class was physically declared by an on-disk module, defer to
# # the absolute filename of that module.
# #
# # Note that arbitrary modules need *NOT* declare the "__file__" dunder
# # attribute. Unlike most other core Python objects, modules are simply
# # arbitrary objects that reside in the "sys.modules" dictionary.
# if func_module_name:
# func_origin_label = getattr(
# modules[func_module_name], '__file__', func_origin_label)
#
# # Return this label.
# return func_origin_label
# ....................{ PRIVATE ~ constants }....................
_LAMBDA_CODE_FILESIZE_MAX = 1000000
'''
Maximum size (in bytes) of files to be safely parsed for lambda function
declarations by the :func:`.get_func_code_or_none` getter.
'''
# ....................{ PRIVATE ~ classes }....................
class _LambdaNodeUnparser(NodeVisitor):
'''
**Lambda node unparser** (i.e., object decompiling the abstract syntax tree
(AST) nodes of *all* pure-Python lambda functions defined in a
caller-specified block of source code into the exact substrings of that
block defining those lambda functions by applying the visitor design pattern
to an AST parsed from that block).
The public :func:`.get_func_code_or_none` getter internally instantiates
this private helper class to decompile AST lambda nodes.
Attributes
----------
lambdas_code : List[str]
List of one or more **source code substrings** (i.e., of one or more
lines of code) defining each of the one or more lambda functions
starting at line :attr:`_lambda_lineno` of the code from which the AST
visited by this visitor was parsed.
_lambda_lineno : int
Caller-requested line number (of the code from which the AST visited by
this object was parsed) starting the definition of the lambda functions
to be unparsed by this visitor.
'''
# ................{ INITIALIZERS }................
def __init__(self, lambda_lineno: int) -> None:
'''
Initialize this visitor.
Parameters
----------
lambda_lineno : int
Caller-specific line number (of the code from which the AST visited
by this object was parsed) starting the definition of the lambda
functions to be unparsed by this visitor.
'''
assert isinstance(lambda_lineno, int), (
f'{repr(lambda_lineno)} not integer.')
assert lambda_lineno >= 0, f'{lambda_lineno} < 0.'
# Initialize our superclass.
super().__init__()
# Classify all passed parameters.
self._lambda_lineno = lambda_lineno
# Initialize all remaining instance variables.
self.lambdas_code: List[str] = []
def visit_Lambda(self, node):
'''
Visit (i.e., handle, process) the passed AST node encapsulating the
definition of a lambda function (parsed from the code from which the AST
visited by this visitor was parsed) *and*, if that lambda starts on the
caller-requested line number, decompile this node back into the
substring of this line defining that lambda.
Parameters
----------
node : LambdaNode
AST node encapsulating the definition of a lambda function.
'''
# If the desired lambda starts on the current line number...
if node.lineno == self._lambda_lineno:
# Decompile this node into the substring of this line defining this
# lambda.
self.lambdas_code.append(ast_unparse(node))
# Recursively visit all child nodes of this lambda node. While doing
# so is largely useless, a sufficient number of dragons are skulking
# to warrant an abundance of caution and magic.
self.generic_visit(node)
# Else if the desired lambda starts on a later line number than the
# current line number, recursively visit all child nodes of the current
# lambda node.
elif node.lineno < self._lambda_lineno:
self.generic_visit(node)
#FIXME: Consider raising an exception here instead like
#"StopException" to force a premature halt to this recursion. Of
#course, handling exceptions also incurs a performance cost, so...
# Else, the desired lambda starts on an earlier line number than the
# current line number, the current lambda *CANNOT* be the desired lambda
# and is thus ignorable. In this case, avoid recursively visiting *ANY*
# child nodes of the current lambda node to induce a premature halt to
# this recursive visitation.
|