A co-worker asked how global/class variable scoping worked in python today. Specifically, how to access globals/class variables from within a class method. I told him what I knew (global keyword.. yadda yadda.. self.. yadda yadda..) and he was satisfied. Then he asked, "where did you read that?" I thought for a second and realized that I had not really ever read much formal documentation on variable scoping and that I must have picked most of what I knew up from looking at code or just playing around. “What do you mean “playing around”?” he wants to know. “Well,” I said, “I just try different stuff and see what happens.” It occured to me that Python is excessively easy to pick up as you go because it is easy to try things quickly, measure results, and draw conclussions. Some people call this “The Scientific Method”. The conversation ended shortly after but I didn't get the feeling he took me seriously on the trial and error thing. Do most programmers feel that formal documentation is a requirement for learning? I sure don't. I'm positive I learn as much, if not more, scientifically than I do reading documentation. My python-fanboy column for today will thus be on how python lends itself well to those that prefer to learn scientifically.

My thought process when encountering a need for global variables in python probably went something like this:

Me: Need a global variable here.
Little Angel: No you don't. Globals are always bad!
Little Devil: Shaddap.. slap, slap. We just need to do this thing real quick. This isn't java.
Me: Hmm.. Maybe we can just use automatic scoping..

>>> x = 5
>>> def y():
...   print x
...
>>> y()
5

Me: Good. So I just use it then.. Hmm.. but wait, surely there will be name clashes..


>>> x = 5
>>> def y():
...   x = 10
...
>>> print x
5
>>> y()
>>> print x
5
>>> # aha!
>>> def y():
>>>    global.x = 10
  File "<stdin>", line 2
    global.x = 10
          ^
SyntaxError: invalid syntax
>>>    __main__.x = 10
>>> y()
>>> print x
5
>>> # ughh
>>> def y():
>>>   ../x # yea right.
[Ctl-D,Ctl-D]

Me: Sneaky little thing you.. So, you're automatic unless I scope something in local. I'm going to need some help here..

Google: python globals
Me: "18ft snake eats glowing balls of..", huh?

Google: python global variable scope
Me: Better. Here's a good code snip:

x = 5
def somefunc():
global x
   print x

Me: ahh..

>>> x = 5
>>> def y():
...    global x
...    x = 10
...
>>> y()
>>> print x
10

I now know how to use globals in Python. That looks like a lot of work but that probably took all of 2 minutes. I guess I could have bypassed the initial tests and went to Google first but I was able to find out a lot with simple trial and error.

I'm lead to the opinion that there are two kinds of programmers and two kinds of languages. You have the scientific, trial and error, show-me-the-source type hacker and then you have the businessy, formal documentation, show-me-the-sdk type. If I had to slot languages I would say C, Python, Perl, and maybe Lisp all seem to fall into the first category and Java, C++, C# fall into second. Some languages, like the different BASICs, seem to fall somewhere in between.

It seems that one of the key benefits of the “learn as you go” languages, and Python specifically, is that you can apply much of what you've learned in other languages very quickly. I have a decent background in Java, C, and Perl. I'm constantly amazed at how much I already know in python by simply asking myself questions of the form, “If I had to write a programming language that did XXX from YYY, how would I write it?” For example, “If I had to write PACKAGE MANAGEMENT from JAVA, how would I write it?” It would look a lot like Python. “If I had to write LIST and HASH stuff from PERL, how would I write it?” Again, it would look a lot like python (well, it would be a lot less useful, I'm sure).

Python really is a language that you can learn as you go, especially if you have experience in other languages. I'm constantly surprised by how much of the language I already know but don't remember learning. Combine that with the ability to do rapid and productive trial and error'ing and you have a language that is sure to be a hit with the scientific types, as is already clearly established.

This entry has been tagged coding, ramblings, python — follow a tag for an archive of related essays, weblog entries, and bookmarks.

Discuss

  1. There is a big problem with this school of thought – it can only take you so far. Don’t rely 100% on trial-and-error or black-box inspection to give you the knowledge you need – there are surely special cases and things to be sure of when you use any statement or function, period.

    In this case, you happen to figure out the correct approach, but what I recommend is that once your trial-and-error leads you to something that appears to work, you take the time to research your solution (check the python docs on the “global” keyword) and make sure you understand why it works. This is very important – programming by accident is a big mistake.

    Otherwise, I agree that your approach is a good way to find answers. Just follow them up with a little documentation to seal the deal and you'll be all set.

    JJ Noakes on Thursday, December 27, 2007 at 11:01 PM #

  2. One of my favorite things about Python is ‘-i’ on the command line is. This has made it easy to do lots of experimentation quite rapidly. I setup a handful of objects in a “main” == name: block, and then tinker with them interactively.

    I've spent a long time writing Perl code, and didn’t even realize how nice this would have been. I suppose I could have done this vi the Perl debugger, but … Now, if there was only an equivalent to perl’s ‘-c’ command line switch. :)

    Scott

    Scott Wimer on Thursday, December 27, 2007 at 11:07 PM #

  3. I am surprised that you slotted C into the pickup as you go language types. Generally I have observed that pickup as you go languages are only so because of their REPL shells. Some people like me stuck in the “Java” business world are looking for alternatives. Languages like Scala and F# seem to bridge the gap. We can only hope that enterprises understand the productivity gains from these languages and make them mainstream.

    Vagmi on Thursday, December 27, 2007 at 11:10 PM #

  4. Definitely true. I pick up languages as I go typically too. Though, I do like a rich API, much like Java provides.

    Mike on Thursday, December 27, 2007 at 11:46 PM #

  5. I'm currently learning Ruby in much the same way. I'm already proficient in C# and Java, with some C++ and Scheme in my academic background, so learning as I go is faster than starting with documentation or always looking things up. I think most experienced programmers learn in this manner, just to different degrees.

    Matt on Friday, December 28, 2007 at 12:18 AM #

  6. I think there’s something about interpreted languages that makes this especially easy. You can type something in and get an immediate answer and there aren’t a lot of tools to get in the way. (how do I compile this?/where do I publish this?) I also think that there is valuable on reading up on a language in addition to playing. I'm in the process of learning Python and have a background in C++/Java/Scheme/ML so while I know I could get in and make things work, that doesn’t guarantee that I'm doing things the best Python way. Taking 2 days to do some reading has shown me a lot of things quickly that would have likely taken a good amount of playing around (or just things that aren’t usually in other languages, so I'm not looking for them, but they turn out to be what makes Python great).

    Kimberly on Friday, December 28, 2007 at 02:54 PM #

  7. I find it interesting that you mentioned your ‘porting’ of knowledge from other languages into python. Python was the first language that I really learnt, and remains the only language that I can competently program in (Hobby programmer). However, I can decypher code in Java, Javascript, C, C++, Pascal, Basic and several other languages simply because the language features are similar to how things are done in python. “Oh, creating an instance in javascript is exactly the same, except I have to put ‘new’ at the start.”

    Joal Heagney on Saturday, February 02, 2008 at 10:04 PM #

Leave a comment





(syntax: markdown)