python - Python3 multiple assignment and memory address -


this question has answer here:

after reading this , this, pretty similar question, still cannot understand following behaviour:

a = 257 b = 257 print(a b) #false a, b = 257, 257 print(a b) #true 

when printing id(a) , id(b) can see variables, values assigned in separate lines, have different ids, whereas multiple assignment both values have same id:

a = 257 b = 257 print(id(a)) #139828809414512 print(id(b)) #139828809414224 a, b = 257, 257 print(id(a)) #139828809414416 print(id(b)) #139828809414416 

but it's impossible explain behaviour saying multiple assignment of same values creates pointers same id since:

a, b = -1000, -1000   print(id(a)) #139828809414448 print(id(b)) #139828809414288 

is there clear rule, explains when variables same id , when not?

edit

relevant info: code in question run in interactive mode(ipython3)

this due constant folding optimization in bytecode compiler. when bytecode compiler compiles batch of statements, uses dict keep track of constants it's seen. dict automatically merges equivalent constants.

here's routine responsible recording , numbering constants (as few related responsibilities):

static int compiler_add_o(struct compiler *c, pyobject *dict, pyobject *o) {     pyobject *t, *v;     py_ssize_t arg;      t = _pycode_constantkey(o);     if (t == null)         return -1;      v = pydict_getitem(dict, t);     if (!v) {         arg = pydict_size(dict);         v = pyint_fromlong(arg);         if (!v) {             py_decref(t);             return -1;         }         if (pydict_setitem(dict, t, v) < 0) {             py_decref(t);             py_decref(v);             return -1;         }         py_decref(v);     }     else         arg = pyint_aslong(v);     py_decref(t);     return arg; } 

you can see adds new entry , assigns new number if doesn't find equivalent constant present. (the _pycode_constantkey bit makes sure things 0.0, -0.0, , 0 considered inequivalent.)

in interactive mode, batch ends every time interpreter has run command, constant folding doesn't happen across commands:

>>> = 1000 >>> b = 1000 >>> b false >>> = 1000; b = 1000 # 1 batch >>> b true 

in script, top-level statements 1 batch, more constant folding happens:

a = 257 b = 257 print b 

in script, prints true.

a function's code gets constants tracked separately code outside function, limits constant folding:

a = 257  def f():     b = 257     print b  f() 

even in script, prints false.


Comments

Popular posts from this blog

java - pagination of xlsx file to XSSFworkbook using apache POI -

Unlimited choices in BASH case statement -

apache - How do I stop my index.php being run twice for every user -