Fundamental Function Question (beginner)

MRAB python at mrabarnett.plus.com
Mon Jan 11 13:57:09 EST 2010


Scott wrote:
> When creating a function is there any difference between putting
> everything under the "def" or not?
> 
> Here I created a function called CscoPortNum to convert the network
> port number field in a Cisco syslog string from a an ascii name back
> into its numeric form if required. Does it matter at all that I
> created the translation dictionary first and then started the def?
> 
> # def CscoPortNum(RulL)
> # Accept a single ACL Rule as a List split into individual words and
> # return Port number. Convert from Cisco syslog Port name if required
> portfpth = "\\progra~1\\syslogd\\ACL_Logs\\Port-Translations.txt"
> # Create dictionary of portnames to portnumbers
> portD = {}
> for prtnmS in open(portfpth):
>     prtnmS = prtnmS.rstrip()
>     spltprtL = prtnmS.split(" ")
>     portD[spltprtL[2]] = [spltprtL[1]]
> def CscoPortNum(RulL):
>     if "eq" in RulL:    # Is the Port listed?
>         if RulL[RulL.index("eq")+1][0].isdigit(): # Is it numeric?
> #        if re.search("\d", RulL[RulL.index("eq")+1][0]): # Is it
> numeric?
>             portnum = RulL[RulL.index("eq")+1]     # If numeric, use
> as is.
>         else:
>             # If named, look up numeric translation
>             portnum = portD[RulL[RulL.index("eq")+1]]
>             portnum = str(portnum).strip("[]'")
>     else:  portnum = "noeq"
>     return portnum

There's nothing wrong with building dicts or other lookup tables outside
a function in order to avoid re-creating them every time the function is
called.



More information about the Python-list mailing list