6868FLOAT_PRECISION = 4
6969
7070
71+ from collections import defaultdict
7172import re , types
7273import sys
7374import math
@@ -135,6 +136,22 @@ def encode_primitive(dat):
135136 return dat
136137
137138
139+ # grab a line number like ' <line 2>' or ' <line 2b>'
140+ def create_lambda_line_number (codeobj , line_to_lambda_code ):
141+ try :
142+ lambda_lineno = codeobj .co_firstlineno
143+ lst = line_to_lambda_code [lambda_lineno ]
144+ ind = lst .index (codeobj )
145+ # add a suffix for all subsequent lambdas on a line beyond the first
146+ if ind > 0 :
147+ lineno_str = str (lambda_lineno ) + chr (ord ('a' ) + ind )
148+ else :
149+ lineno_str = str (lambda_lineno )
150+ return ' <line ' + lineno_str + '>'
151+ except :
152+ return ''
153+
154+
138155# Note that this might BLOAT MEMORY CONSUMPTION since we're holding on
139156# to every reference ever created by the program without ever releasing
140157# anything!
@@ -149,6 +166,21 @@ def __init__(self, render_heap_primitives):
149166 self .id_to_small_IDs = {}
150167 self .cur_small_ID = 1
151168
169+ # wow, creating unique identifiers for lambdas is quite annoying,
170+ # especially if we want to properly differentiate:
171+ # 1.) multiple lambdas defined on the same line, and
172+ # 2.) the same lambda code defined multiple times on different lines
173+ #
174+ # However, it gets confused when there are multiple identical
175+ # lambdas on the same line, like:
176+ # f(lambda x:x*x, lambda y:y*y, lambda x:x*x)
177+
178+ # (assumes everything is in one file)
179+ # Key: line number
180+ # Value: list of the code objects of lambdas defined
181+ # on that line in the order they were defined
182+ self .line_to_lambda_code = defaultdict (list )
183+
152184
153185 def get_heap (self ):
154186 return self .encoded_heap_objects
@@ -248,6 +280,16 @@ def encode(self, dat, get_parent):
248280 except TypeError :
249281 pass
250282
283+ # put a line number suffix on lambdas to more uniquely identify
284+ # them, since they don't have names
285+ if func_name == '<lambda>' :
286+ cod = (dat .__code__ if is_python3 else dat .func_code ) # ugh!
287+ lst = self .line_to_lambda_code [cod .co_firstlineno ]
288+ if cod not in lst :
289+ lst .append (cod )
290+ pretty_name += create_lambda_line_number (cod ,
291+ self .line_to_lambda_code )
292+
251293 encoded_val = ['FUNCTION' , pretty_name , None ]
252294 if get_parent :
253295 enclosing_frame_id = get_parent (dat )
0 commit comments