I am writing code to determine the name to which the object is assigned. This is for general debugging work and for further familiarization with the internal components of python.
I structured it as a class decorator, so that all instances of this class will record their names, if possible. The code is quite long, so I will not publish it unless specified. The general technique is such that
decorate the __init__ class method with code to do what I want
set caller = inspect.currentframe().f_back and open inspect.getframeinfo(caller).filename and send it to ast.parse . I am not making any mistakes here because (1) it is just for debugging / profiling / hacking (2) this exact process was “just” completed or the code would not work. Is there a problem with this?
find the ast.Assignment instance that runs the currently executing __init__ method
if len(assignment.targets) == 1 , then there is only one element on the left side, and I can get the name from targets[0].id . In a simple form, such as a = Foo() , then assignment.value is an instance of ast.Call . if it is a literal list (for example, a list), then value will be that list and the key, because the object of interest to me is not assigned a name.
What is the best way to confirm that assignment.value.func is actually a type(obj).__call__ object that interests me. I’m sure that I’m guaranteed that it’s there somewhere or the code will not even work. I just need him to be top notch. The obvious thing to do is take a walk and make sure that it does not contain internal calls. Then I am guaranteed that I have a name. (My reasoning is correct, I'm not sure what his assumptions are). This is not ideal, because if I'm interested in Foo , it can lead me to drop a = Foo(Bar()) , because I don't know if it is a = Bar(Foo()) .
Of course, I can just check assignment.value.func.id , but then someone could do Foobar = Foo or something like that, so I don't want to rely on it too much
Any help would be greatly appreciated. As always, I am interested in any other suggestions or problems that I can ignore.
Also, I'm really surprised that I just needed to come up with the python-internals tag.
python python-internals
aaronasterling
source share