How to "generalize" a function?

Scott David Daniels Scott.Daniels at Acm.Org
Sun Apr 24 20:02:32 EDT 2005


Alexander Schmolck wrote:
> [1]  Best practice would be something like this (don't worry to much about it
>      -- it just ensures the file is properly closed, even if something goes
>      wrong):
> 
>         confFile = None
>         try:
>             confFile = open(networkConf, 'w')
>             confFile.writelines(conf)
>         finally:
>             if confFile: confFile.close()
> 

A clearer equivalent is:
     confFile = open(networkConf, 'w')
     try:
         confFile.writelines(conf)
     finally:
         confFile.close()


You did not say whether you are looking to replace all, the first,
or the last occurrence of your search target.  Assuming you really
mean all lines and the first occurrence on those lines:

     def replaces(source, search, replacement):
         '''Replace first of search on lines with replacement'''
         pat = re.compile(search)
         for line in source:
             yield re.sub(pat, replacement, line, 1)

And your application might go like:

     input = open(networkConf, 'r')
     part1 = replaces(input, 'address', 'ip')
     part2 = replaces(part1, 'netmask', 'mask')
     result = list(part2)
     input.close()
     output = open(networkConf, 'w')
     try:
         output.writelines(result)
     finally:
         output.close()


--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list