newbie questions

Steven Bethard steven.bethard at gmail.com
Sat Dec 11 08:21:11 EST 2004


houbahop wrote:
> Thank you everyone, but I still not understand why such a comon feature like 
> passing parameters byref that is present in most serious programming
> languages is not possible in a clean way,here in python.

I understand from this statement that Java is not a serious programming 
language? ;)

> I have the habit to never use globals as far as possible and this involve 
> that my main function is passing some parameters by reference to subs to 
> allow them to modify the vars.

I don't see why lack of pass-by-reference would force you to use globals...

 >>> class C(object):
...     def __init__(self):
...         self.list = []
...     def fill(self, iterable):
...         self.list.extend(iterable)
...     def empty(self):
...         self.list = []
...
 >>> c = C()
 >>> c.list
[]
 >>> c.fill(pow(x, 3, 29) for x in range(10))
 >>> c.list
[0, 1, 8, 27, 6, 9, 13, 24, 19, 4]
 >>> c.empty()
 >>> c.list
[]

Or by globals do you mean instance variables?  If you don't want any 
instance variables (which means you don't really want OO), you can still 
clear your list as long as you have any name bound to the list object:

 >>> def clear(lst):
...     while lst:
...         lst.pop()
...
 >>> x = [pow(x, 7, 19) for x in range(10)]
 >>> x
[0, 1, 14, 2, 6, 16, 9, 7, 8, 4]
 >>> clear(x)
 >>> x
[]

or alternatively:

 >>> def clear(lst):
...     lst[:] = []
...
 >>> x = [pow(x, 7, 19) for x in range(10)]
 >>> x
[0, 1, 14, 2, 6, 16, 9, 7, 8, 4]
 >>> clear(x)
 >>> x
[]

Note that neither of these functions requires pass-by-reference; the lst 
local in the function is not the same name as the x local outside the 
function.  But since you're basically just passing a "pointer" by value, 
both "variables" still "point" to the same object (or in Python terms, 
both "names" are "bound" to the same object).  To apply an affect that 
is visible to all names bound to an object, you simply need to mutate 
the object.  In the cases above, this is just a matter of using the 
appropriate object method (list.pop or list.__setslice__ respectively 
above).

Is this so bad?

Steve



More information about the Python-list mailing list