When defining a python function, I find it hard to debug if I had a typo in a variable name and that variable already exists in the outer scope. I usually use similar names for variables of the same type of data structure, so if that happens, the function still runs fine but just returns a wrong result. So is there a way to prevent python functions to read outer scope variables?
-
2Use more meaningful variable names. – ILostMySpoon May 07 '15 at 17:58
-
and start using classes to divide things up. – MrAlexBailey May 07 '15 at 17:59
-
be careful when you coding, or get a better IDE to help you. – Haifeng Zhang May 07 '15 at 17:59
-
@ILostMySpoon the variables do have meaningful names. They just have similar names. – qkhhly May 07 '15 at 18:06
2 Answers
You're going against the point of having Scopes at all. We have local and global scopes for a reason. You can't prevent Python from seeing outer scope variables. Some other languages allow scope priority but Python's design principles enforce strong scoping. This was a language design choice and hence Python is the wrong language to try to prevent outer scope variable reading.
Just use better naming methodologies to ensure no confusion, you change up variable names by using the Find-Replace function that most text editors provide.
- 4,911
- 4
- 31
- 51
They say you should avoid usage of global variables if possible. Also, keep in mind, that python has rules on searching variables in the specific order.
So you can avoid checking global variables only if you will delete them, but it makes usage of global variables useless.
- 1
- 1
- 1,726
- 1
- 20
- 23