[Tutor] beginning to code
bartc
bc at freeuk.com
Fri Sep 22 08:47:10 EDT 2017
On 22/09/2017 13:34, Steve D'Aprano wrote:
> On Fri, 22 Sep 2017 09:24 pm, Marko Rauhamaa wrote:
>> 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.
> 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.
And being able to pass any lvalue expression, not just simple variable
names. Such as a[i] or x.y, provided the term is mutable.
(To make it work would require a new reference type. And extra versions
of the byte-codes or whatever is used to evaluate terms such as:
a, a[i], x.y
that evaluate a reference rather than the value. So LOADFASTREF as well
as LOADFAST)
--
bartc
More information about the Python-list
mailing list