I have a question about global scope in python.
I make this script and works but I don’t know why:
#! /bin/python3
# -*- coding: UTF-8 -*-
data = []
stats = {'white':0, }
def main():
global data
with open(args.finput, 'r') as f:
data = f.readlines()
rwhitespaces()
with open(foutput, 'w') as f:
for line in data:
f.write(line)
print(stats)
def rwhitespaces():
cnt = 0
for line in data:
if line == '\n':
data.pop(cnt) # Modifing data var without global keywork and works, why??
stats['fistro'] = 1 # Modifing stats var without global keywork and works why??
cnt += 1
if __name__ == "__main__":
main()
So I’m misunderstanding something with global scope can someone explain me???
Thanks and sorry my bad english
This works because you are not changing the reference, but rather accessing a mutable object, and getting it to perform changes upon itself.
globalis required to assign a new value to a globally scoped variable (x = blah), but it isn’t needed to merely access one. As when you dodata.pop(cnt)all you are doing is accessing the variable, you can do it without using theglobalkeyword.In short, it’s not about changing properties of the object, it’s about assignment of an object to a variable.