On Fri, Sep 22, 2017 at 9:24 PM, Marko Rauhamaa <ma...@pacujo.net> wrote:
> bartc <b...@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

Sure, let me just put that into a function. CPython 3.7, although I'm
pretty sure most CPython versions will do the same, as will several of
the other Pythons.

(Side point: Your slot_ref function is rather bizarre. It's a closure
AND a class, just in case one of them isn't sufficient. The following
code is copied and pasted from two of your posts and is unchanged
other than making try_swapping into a function.)

>>> def slot_ref(dict_or_array, key_or_index):
...        class SlotRef:
...            def get(self): return dict_or_array[key_or_index]
...            def set(self, value): dict_or_array[key_or_index] = value
...        return SlotRef()
...
>>> def swap(ref_a, ref_b):
...        a, b = ref_a.get(), ref_b.get()
...        ref_a.set(b)
...        ref_b.set(a)
...
>>> def try_swapping():
...    x = 10
...    y = "Z"
...    swap(slot_ref(locals(), "x"), slot_ref(locals(), "y"))
...    print("x, y =", x, y)
...
>>> try_swapping()
x, y = 10 Z

Strange... doesn't seem to work. Are you saying that Python is
pass-by-reference outside of a function and pass-by-value inside?
Because that'd be just insane.

Or maybe what you have here isn't a real reference at all.

ChrisA
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to