How to "generalize" a function?
jfj
jfj at freemail.gr
Mon Apr 25 05:32:15 EDT 2005
Thomas Köllmann wrote:
> Hi, everybody!
>
> I'm teaching myself Python, and I have no experience in programming
> apart from some years of shell scripting. So, please bear with me.
>
> These two funktions are part of an administrative script I've set
> myself as a first lesson, and, as you will see, they're practically the same,
> except for one variable. So I'd like to weld them together -- but I
> can't find out how to.
Pass the variable as an argument probably.
But because generally you wouldn't want to recompile the regexp (this
should be done once), you could say:
# untested
def makewriter (regexp_string):
def writeFunc(ip, regex=re.compile(regexp_string)):
confFile = open(networkConf, 'r')
conf = confFile.readlines()
confFile.close
for line in conf:
if regex.search(line):
addressLine = line
addressLineNum = conf.index(addressLine)
address = string.split(addressLine, ' ')
address[1] = ip + "\n"
conf[addressLineNum] = string.join(address)
confFile = open(networkConf, 'w')
confFile.writelines(conf)
confFile.close
return writeFunc
writeIP=makewriter('(.*)address(.*)')
writeMask=makewriter('(.*)netmask(.*)')
This is rather advanced python programming though, but it shows
cool dynamic function creation features and it's never early to
get into it;)
jfj
More information about the Python-list
mailing list