python - Why is it valid to assign to an empty list but not to an empty tuple? -


this came in a recent pycon talk.

the statement

[] = [] 

does nothing meaningful, not throw exception either. have feeling must due unpacking rules. can tuple unpacking lists too, e.g.,

[a, b] = [1, 2] 

does expect. logical consequence, should work, when number of elements unpack 0, explain why assigning empty list valid. theory further supported happens when try assign non-empty list empty list:

>>> [] = [1] traceback (most recent call last):   file "<stdin>", line 1, in <module> valueerror: many values unpack 

i happy explanation, if same true tuples. if can unpack list 0 elements, should able unpack tuple 0 elements, no? however:

>>> () = ()   file "<stdin>", line 1 syntaxerror: can't assign () 

it seems unpacking rules not applied tuples lists. cannot think of explanation inconsistency. there reason behavior?

the comment @user2357112 seems coincidence appears correct. relevant part of python source code in python/ast.c:

switch (e->kind) {     # several cases snipped     case list_kind:         e->v.list.ctx = ctx;         s = e->v.list.elts;         break;     case tuple_kind:         if (asdl_seq_len(e->v.tuple.elts))  {             e->v.tuple.ctx = ctx;             s = e->v.tuple.elts;         }         else {             expr_name = "()";         }         break;     # several more cases snipped } /* check error string set switch */ if (expr_name) {     char buf[300];     pyos_snprintf(buf, sizeof(buf),                   "can't %s %s",                   ctx == store ? "assign to" : "delete",                   expr_name);     return ast_error(c, n, buf); } 

tuples have explicit check length not 0 , raise error when is. lists not have such check, there's no exception raised.

i don't see particular reason allowing assignment empty list when error assign empty tuple, perhaps there's special case i'm not considering. i'd suggest (trivial) bug , behaviors should same both types.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -