In the python example below, methods and attributes seem to be out of scope but they still work, what is happening?
for module in output:
a = 1
attributes=[]
methods=[]
for branch in module[2]:
for leaf in branch[2]:
if leaf[0]=="method":
methods.append(leaf[1])
if leaf[0]=="attribute":
attributes.append(leaf[1])
print methods
print attributes
print module[0]
print a
but if I outdent one more level it stops working
for filename in os.listdir("."):
print filename
fName, fExtension = os.path.splitext(filename)
print fName, fExtension
if fExtension == ".idl":
f = open(filename)
idl = f.read()
f.close()
output = parse(idl)
pprint.pprint(output)
root={}
for module in output:
a = 1
attributes=[]
methods=[]
for branch in module[2]:
for leaf in branch[2]:
if leaf[0]=="method":
methods.append(leaf[1])
if leaf[0]=="attribute":
attributes.append(leaf[1])
print methods
print module[0]
it says: NameError: name ‘methods’ is not defined
I’m using python 2.7
As indicated in the comments,
forloops,whileloops,ifstatements, etc. do not create a new scope. In fact, the only things that create a new scopes are functions, classes, modules and methods. Therefore, when you create a new variable inside aforloop, it is available outside of that loop because they share the same scope.