[Python-ideas] Javascript Destructuring Assignment
Ron Adam
rrr at ronadam.com
Thu Mar 8 05:23:08 CET 2007
Jim Jewett wrote:
> On 3/7/07, Ron Adam <rrr at ronadam.com> wrote:
>> The example from above could then be...
>>
>> >>> data = [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10]
>> >>> a, b, c, d, e, f, g = "[[,,*],[,,*],*]" %% data
>>
>> >>> print a, b, c, d, e, f, g
>> 1 2 [3, 4] 5 6 [7, 8] [9, 10]
>
> ...
>
>> >>> data = [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10]
>> >>> a, b, c, d = ",,,*" %% "[,[],,]" %% data
>> >>> print a, b, c, d
>> [1, 2, 3, 4] 5 6 [7, 8, 9, 10]
>
> ...
>
>> This type of abstraction may make it easier to interface different
>> types of
>> objects and data structures dynamically.
>
> I can see how this might be made efficient.
>
> I'm not seeing how I could ever maintain code that used it.
Yes, that would be a problem.
(And I need to resist posting things like this because then I feel
obligated to try to explain them. ie... wait 24 hours and if it still
seems like a good idea, then post it.)
Regarding maintaining code:
For interfacing purposes you would probably define the re-packers with the
data and not where you actually use them. And use in-line comments as well.
Trying a different format. (This can't be a serious proposal unless it
can be made simple to understand.)
'[]' for unpack items, these can be nested.
'.' a single unchanged item
'.n' for next n unchanged items
'*n' for packing next n items
'*' pack the rest of the items, use at the end only.
'' Null, don't change anything
* Doing it in two steps is the easy way, unpack+repack.
* Both unpacking/repacking can be done in one step
if the items are aligned.
* partial unpacking/repacking is perfectly ok.
(if it does what you want)
data_source_v1 = [[1, 2, 3, 4], [5, 6, 7, 8], 9, 10]
unpack_v1 = "[[][]..]"
repack_to_v2 = "..*2..*2*" # 1,2,[3,4],5,6,[7,8],[9,10]
data_source_v2 = [1, 2, [3, 4], 5, 6, [7, 8], [9, 10]]
unpack_v2 = "[..[]..[][]]"
repack_to_v1 = "*4*4.." # [1,2,3,4][5,6,7,8],9,10
def interface_v1(data, unpack='', repack=''):
a, b, c, d = repack %% unpack %% data
# Do something with a thru d.
def interface_v2(data, unpack='', repack=''):
a, b, c, d, e ,f, g = repack %% unpack %% data
# do something with a thru g
# use data sources with interface v1
interface_v1(data_source_v1) # use v1 data as is
interface_v1(data_source_v2, unpack_v2, repack_to_v1)
# use data sources with interface V2
interface_v2(data_source_v2) # use v2 data as is
interface_v2(data_source_v1, upack_v1, repack_to_v2)
Decorators probably currently fit this use better I think.
Cheers,
Ron
More information about the Python-ideas
mailing list