Declaring A Function Argument As Global?
Mark Jackson
mjackson at alumni.caltech.edu
Thu Jan 16 12:42:40 EST 2003
Tim Daneliuk <tundra at tundraware.com> writes:
> I want to be able to write a generic list handling function which slices
> a list, but I don't want to have to return the modified list
> to do so. In other words, I purposely want the function to have
> a side-effect which modifies the list handed to it. For example:
>
>
> def lhandler(list):
> list = list[1:]
>
> mylist = [1,2,3]
>
> lhandler(mylist) doesn't change mylist (because the assignment creates
> a local variable by Python scoping rules), but that's exactly what
> I want it to do. So far, I've only come up with two solutions:
>
> 1) return the modified value - for various reasons, this is
> an ugly solution in my application.
>
> 2) Pass the *name* of the list into the function and do something
> truly ugly like:
>
> globals()[name] = globals()[name][1:] # Yuk!
>
> Is there another way?
def lhandler(list):
list.remove(list[0])
modifies the list in place as required by the example given. Rewriting
what you *actually* want to do using only in-place list methods may be
less straightforward or have performance implications, of course.
--
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
Well. . .old people with really good memories think I'm
clever. So there!! - Huey Freeman (Aaron McGruder)
More information about the Python-list
mailing list