Reputation: 10189
I am using Python 3 and I am trying to check if the current method has been called from a specific method. This one has not to be necessarily the parent call, only one of the ancestors.
Example:
I need to know if the method F is called from the method C. The method A calls B, B calls C, C calls D, D calls E, E calls F. So the ancestor methods of F are [A, B, C, D, E]. Since C is in this list, my method returns
True
, otherwise returnsFalse
.
I have two solutions (I will replace the method names with parameters):
First one, which I think is faster:
for frame in inspect.stack():
if frame.function == 'C':
return True
Second one:
methods = [frame.function for frame in inspect.stack()]
if 'C' in methods:
return True
Is the first solution better? Any suggestion to improve it? Is this already made in any library?
Upvotes: 1
Views: 63
Reputation: 43300
I'd go with solution c, any
any(f.function == 'C' for f in inspect.stack())
In terms of the two you've shown, potentially the first is faster since you're short circuiting within the loop and don't need to create an entire list, to then iterate over a second time
I say potentially because it would depend on how large the stack is as to how much better off it'd be
Upvotes: 4