osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Can global variable be passed into Python function?


On Sat, 22 Feb 2014 09:28:10 +0200, Marko Rauhamaa wrote:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info>:
> 
>> But your code doesn't succeed at doing what it sets out to do. If you
>> try to call it like this:
>>
>> py> x = 23
>> py> y = 42
>> py> swap(x, y)
>> Traceback (most recent call last):
>>   File "<stdin>", line 1, in <module>
>>   File "<stdin>", line 2, in swap
>> AttributeError: 'int' object has no attribute 'get'
>>
>> not only doesn't it swap the two variables, but it raises an exception.
>> Far from being a universal swap, it's merely an obfuscated function to
>> swap a few hard-coded local variables.
> 
> You are calling the function wrong. Imagine the function in C. There,
> you'd have to do this:
[...]


Sorry, I misunderstood you. When you called it a universal swap function, 
I thought you meant a universal swap function. I didn't realise you 
intended it as a demonstration of how to emulate a C idiom using overly-
complicated Python code *wink*

If you want to emulate pointers in Python, the simplest way is to use 
lists as pseudo-pointers.

# think of ptr[0] as pointer dereferencing
# think of [value] as quasi "address of" operator
def swap(p, q):
    p[0], q[0] = q[0], p[0]

x = ["anything"]
y = ["something"]
z = [23]

swap(x, y)
swap(x, z)

print(x[0], y[0], z[0])
=> prints "23 anything something"


But why bother to write C in Python? Python makes a really bad C, and C 
makes a really bad Python.



-- 
Steven