Friday, 14 February 2014

Week 3 SLOG - Scope

I found the section on scope in this week's lectures very interesting. After going to the lecture on scope, I realized that quite often the bugs I find in my code are to do with scope, which I didn't realize before. I can be sloppy with variable names, so I find myself reusing a variable name several times throughout my code to reference several different things in several different scopes. This tends to return unexpected results a lot of the time, but I've gotten away with it by just tweaking a couple of names here and there until it works. Now that I understand scope, I realize that I really need to be more careful with my variable names; it will help me escape a lot of avoidable problems.

In the lecture, we looked at some code that played around with scope - names.py. During the lecture, I found it slightly confusing - and it was supposed to be, so that was okay! When I got home, I took a look at the code again. At first, I didn't understand why when asked to print spam, the code printed nonlocal spam after both the nonlocal spam assignment and the global spam assignment. Now I understand that it's because Python looks to the nonlocal scope before it looks to the global scope. So even after a global spam is assigned, Python still looks to the nonlocal scope first, and returns the value of spam from there before it ever even gets to the global value.

Even though scopes can be confusing, I think that as long as you take the time to carefully trace out what's going on in your code, you can always figure out how Python is using the different scopes to look at your variables.

No comments:

Post a Comment