[Tutor] Callable? Whats callable?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 26 Aug 2001 13:40:30 -0700 (PDT)


On Sun, 26 Aug 2001, epoch7 wrote:

> alright. so i fixed the error in y. originally i started putting in the
> read()s and stuff to be able to fix an error/find a workaround.
> i was getting, here's how i got that error:
> 
> import re
> 
> file1 = raw_input("Name of file to convert: ")
> file2 = raw_input("Name of file to output to: ")
> in_file = open(file1, "r")
> out_file = open(file2, "w")
> x = in_file.read()
> text = re.compile('url=(\w*)&', re.IGNORECASE)
> y = text.findall(x)
> y.write(text)
> in_file.close()
> out_file.close()


[Warning: Some subjective and preachy comments in this message.]


It might be better to call 'x' your 'text' instead; I got confused for a
moment by:

> x = in_file.read()
> text = re.compile('url=(\w*)&', re.IGNORECASE)
> y = text.findall(x)


Renaming the variable takes more typing, but it might help:

###
file_text = in_file.read()
regex = re.compile('url=(\w*)&', re.IGNORECASE)
matches = regex.findall(file_text)
###

When we use descriptive names, then sometimes it's easier to catch bugs
later on in the code.  For example, with the code:

> y = text.findall(x)
> y.write(text)


if we substitute with slightly different variable names:

###
matches = regex.findall(file_text)
regex.write(matches)
###

then it's a lot clearer that there's something wacky happening here:
instead of writing our result into the file, we're telling writing it back
into the regular expression.  That's not "write": we want to write it into
our out_file instead.


Hope this helps!