Python Args By Reference

Donn Cave donn at drizzle.com
Wed May 11 02:17:06 EDT 2005


Quoth "ncf" <nothingcanfulfill at gmail.com>:
...
| The two issues I am having in grasping all of this are as follows:
| 1) Being new to Python, terms like mutable and immutable. Although I
| have probably dealt with them in other languages, the terms by
| themselves are a little confusing, but managable overall, so this issue
| isn't so big.

It's often introduced in a confusing way.  We just say it's mutable
if it has one or more functions that modify its contents.  There
isn't any other distinction, any other difference than that.

| 2) LARGELY, my issue is as demonstrated by the following code. I was
| trying to accomplish an effect similar to what is possible in C.
| (Trying to make a pure-python FIPS-180-2 compliant implementation of
| the SHA-256 algorithm for more Python practice and to put into some
| code for a *trial* secure protocol.)
| Example C Code:
| #define P(a,b,c,d,e,f,g,h,x,K) \
| { \
| temp1 = h + S3(e) + F1(e,f,g) + K + x; \
| temp2 = S2(a) + F0(a,b,c); \
| d += temp1; h = temp1 + temp2; \
| }
|
| Python Code:
| def P(a,b,c,d,e,f,g,h,x,K):
|     temp1 = h + S3(e) + F1(e,f,g) + K + x
|     temp2 = S2(a) + F0(a,b,c)
|     d += temp1; h = temp1 + temp2
|
| The reason why it'd be a pain to implement this by any of the methods
| provided in the Python FAQs is that SHA-256 rotates the variable order
| in the calls. Example code:
|     P( A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98 );
|     P( H, A, B, C, D, E, F, G, W[ 1], 0x71374491 );
|     P( G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF );
|     P( F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5 );
|     P( E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B );
|     P( D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1 );
|     P( C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4 );
|     P( B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5 );
|     P( A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98 );
|
| Since I cannot simply do it the way I had originally seen it, would
| there be an alternative method to proforming the operations that I am
| missing?

I could be missing something, but I think you just have to suck it up
and do it one of the other two ways:

1.  The more or less functional way:  the function doesn't
    have any side effects.  It just returns the values it
    computes, and it's for the caller to bind them to variables.

      D, H = P(A, B, C, D, E, F, G, H, W[0], 0x428A2F98)
      C, G = (H, A, B, C, D, E, F, G, W[1], 0x71374491)
      ...

2.  The OOP way:  each object has the appropriate function
    that modifies its content value.  That looks like a
    big waste of time to me, but I mention it for conceptual
    completeness.

	Donn Cave, donn at drizzle.com



More information about the Python-list mailing list