Weird scoping rules

Weird scoping rules

I showed a cunning coder some code like this:

  1. with open(textfile) as lines:
  2. record = {}
  3. for line in lines:
  4. key, value = line.rstrip('\n').split(': ', 1)
  5. record[key] = value
  6. do_something_with(record)

He asked:

"How is that last reference to record in scope?"

You see, he has a lot of experience with JVM languages. And in those languages, this "record" variable would be out of scope, on that last line.

A compile-time error, in other words.

So I explained that Python's semantics are a bit different...

... because in Python, if you create a variable inside a "with" or "for" block, that variable stubbornly persists after that block closes. By design.

Once I explained it, he "got" it, of course. Right away.

But on his own, he would never have thought this would work.

It made me wonder about the mental models we "pick up" from other languages...

And how those assumptions we carry, which are true in other languages... But not in Python...

Hold us back, without even realizing it.

Personally, Python was my 6th or 7th programming language. So I've caught myself doing this a LOT.

And it's worth pulling on that thread. When you do notice this happening, don't ignore it.

Instead, recognize this is an opportunity to update your mental model for how Python works...

And follow through, by digging into the the docs, or writing little toy programs to see what works and what doesn't, et cetera.

Make this a habit, and it won't be long before you find yourself getting even more out of the language.

Book Bootcamp