Is it possible to identify if we are in the middle of a loop?
I want to make the class automatically identify if the variable came from an iterator or not.
I checked inspect module and didn't succeed. Maybe there is some scope identifier or some brilliant magic methods manipulation that can flag when a code runs inside a loop.
Here's an example to make myself clear. How to set inside_loop Student attribute?
class Student:
def __init__(self, id):
self.id = id
self.inside_loop = ???
def print_grade(self):
if self.inside_loop:
print("you are inside a loop")
else:
print("checking grade...")
>>> S = Student(1)
>>> S.print_grade()
>>> checking grade...
>>> student_ids = [1, 2, 3]
>>> for student in student_ids:
>>> S = Student(student)
>>> S.print_grade()
>>>
>>> you are inside a loop
>>> you are inside a loop
>>> you are inside a loop
Thanks in advance.