Wednesday, September 14, 2011

Googling for Python 3 Documentation

Here's a game:

You want to find the documentation for the open() function in Python 3. How do you Google?

'python open()' gets you right to the relevant page for Python 2. Is there anything that gets you to:

or even

Adding py3k to the search, or 3 or 3000, just confuses the issue, Google no longer sends you to documentation, but to resources on upconverting your Python 2 projects.

The fastest way I've found is to head to the py2 page, then add '/py3k' right before library (note the URL structure above). Wish I could bounce through google and get there more directly though!

Sunday, September 4, 2011

Python: Open with Raw Strings

When you open a file on a windows system in Python, your command may look something like this:

open("C:\Users\...\file.yml"...)

The problem is that the windows slashes will make the following characters special. You have two options:

1) You can escape each slash with another slash:
open("C:\\Users\\...\\file.yml"...)

2) You can use a raw string. Raw strings don't let the slash modify anything, they just take the string as is. You signal them with a naked r right in front of the string, like so:

open(r"C:\Users\...\file.yml"...)

You also need to specify how to open the file (see the open command). I just want to read the file, so I often do this:

open(r"C:\Users\directory\file.yml",r)

But wait! Suddenly I get an error! Python is complaining about my r:

"NameError: name 'r' is not defined"

I start to panic. Maybe raw string support broke in the latest version of Python!

It takes me about 15 minutes of furious googling before I realize my mistake. The signal for the open command, that's the 'r' causing a problem. The first r is naked, unquoted. But the open command's argument is still a string, it still needs some sort of quotation mark.

The correct line is:

open(r"C:\Users\directory\file.yml",'r')

Hopefully I'll remember to reread this post first next time...