Python help

Erik Price erikprice at mac.com
Fri Feb 6 09:12:33 EST 2004


 
On Thursday, February 05, 2004, at 06:14PM, Cole Tuininga <colet at code-energy.com> wrote:


>This is a very subtle one.  The point is that in a method definition
>within an object, you never want to assign a mutable type (namely, the
>empty list) to an argument.  Weird behavior will occur.

I totally forgot about that!  Excellent observation.  According to the language reference, it's because:

<explanation src ="http://python.org/doc/current/ref/function.html">

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same ``pre-computed'' value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended.

</explanation>

>> def main(args=sys.argv):
>
>One point about the above line - if you're testing from a python prompt,
>you'll need to pass your arguments in as a list.  So for instance,
>>>> main( ["/etc/group"] )
>
>rather than just
>
>>>> main ( "/etc/group" )
>
>Otherwise, the next line would generate some rather peculiar behavior.
>
>>     f = file(args[1], "r")

Yes, exactly.  Although, I think you meant that the file name should be in the second element of the list passed into the main() function, because in "sys.argv" the first element (sys.argv[0]) is the script name, and arguments start at sys.argv[1].

>Also, below, it looks like you started out wanting to use a list, but
>switched to a dict:

Yes, I started out by reproducing Paul's original script (which used a dict) exactly, and then I refactored the dict to a list when I realized that the main() function didn't really need to know the Group object's name anymore.  I should have tested this code, but I was in a rush.

>These items aren't meant as bashing - I know you said you wrote it
>without testing.  I'm just trying to clarify.  8)

Not at all.  Thanks for your input, esp about the mutable default argument in a class method declaration.  And, my apologies to the list for sending the email thrice; mail client problems.


Erik



More information about the gnhlug-discuss mailing list