[Tutor] beginning to code

Steve D'Aprano steve+python at pearwood.info
Fri Sep 22 08:34:19 EDT 2017


On Fri, 22 Sep 2017 09:24 pm, Marko Rauhamaa wrote:

> bartc <bc at freeuk.com>:
> 
>> On 22/09/2017 10:23, Marko Rauhamaa wrote:
>>> However, Python doesn't need any language changes to implement memory
>>> slots. A memory slot could be defined as any object that implements
>>> "get()" and "set(value)" methods:
>>
>> I didn't understand your examples.
>>
>> Can Python be used to write, say, a swap() function that works with any
>> argument types (not just classes or lists)? Example:
>>
>>     def swap(&a,&b):        # made up syntax
>>         a, b = b, a
>>
>>     x=10
>>     y="Z"
>>     swap(x,y)
>>     print (x,y)             # "Z" and "10"
> 
> Yes, following my recipe:
> 
>    def swap(ref_a, ref_b):
>        a, b = ref_a.get(), ref_b.get()
>        ref_a.set(b)
>        ref_b.set(a)
> 
>    x = 10
>    y = "Z"
>    swap(slot_ref(locals(), "x"), slot_ref(locals(), "y"))
>    print(x, y)             # "Z" and 10


No, you failed to follow Bart's instructions and answered a different question.

"Can you pulverise this granite boulder with your bare hands?"

"Sure! I just need to use this sledge hammer, and pulverise this small sandstone
rock instead."


You have to pass x and y, not strings 'x' and 'y'. The swap procedure needs to
accept any variable, given as ordinary bare names swap(x, y), not written as
strings, or by hard-coding x and y as the variables to swap, or by using a
string and passing it to exec, or any other loophole.

Also, you're assuming that locals() is writable, which in the most general case
it is not. Try using locals from inside a function, rather than in the global
scope.

You made a good attempt to emulate pass by reference via an extra layer of
indirection. Pity that it doesn't solve the problem and doesn't work.

Here's an easy way to emulate pass by reference which works in any scope: use a
list.


def swap(a, b):
    a[0], b[0] = b[0], a[0]


a = [1]
b = [2]
swap(a, b)
assert a[0] == 2 and b[0] == 1


It's not proper pass by reference, and so will still fail Bart's test, because
you need to manually add an extra layer of redirection (using a list). Its like
using a pointer in C to emulate references, compared to having actual language
support for them like in Pascal or C++.

But if I wanted to write a Pascal interpreter in Python, I could use something
like this to implement Pascal var parameters.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list