cpython

Tuple slicing not returning a new object as opposed to list slicing

心已入冬 提交于 2019-12-04 01:17:51
In Python (2 and 3). Whenever we use list slicing it returns a new object, e.g.: l1 = [1,2,3,4] print(id(l1)) l2 = l1[:] print(id(l2)) Output >>> 140344378384464 >>> 140344378387272 If the same thing is repeated with tuple, the same object is returned, e.g.: t1 = (1,2,3,4) t2 = t1[:] print(id(t1)) print(id(t2)) Output >>> 140344379214896 >>> 140344379214896 It would be great if someone can shed some light on why this is happening, throughout my Python experience I was under the impression empty slice returns a new object. My understanding is that it's returning the same object as tuples are

python function(or a code block) runs much slower with a time interval in a loop

你。 提交于 2019-12-03 21:30:46
I notice a case in python, when a block of code, nested in a loop, runs continuously, it is much faster than running with some .sleep() time interval. I wonder the reason and a possible solution . I guess it's related to CPU-cache or some mechanism of cPython VM. ''' Created on Aug 22, 2015 @author: doge ''' import numpy as np import time import gc gc.disable() t = np.arange(100000) for i in xrange(100): #np.sum(t) time.sleep(1) #--> if you comment this line, the following lines will be much faster st = time.time() np.sum(t) print (time.time() - st)*1e6 result: without sleep in loop, time

'{0}'.format() is faster than str() and '{}'.format() using IPython %timeit and otherwise using pure Python

扶醉桌前 提交于 2019-12-03 16:16:21
问题 So it's a CPython thing, not quite sure that it has same behaviour with other implementations. But '{0}'.format() is faster than str() and '{}'.format() . I'm posting results from Python 3.5.2 , but, I tried it with Python 2.7.12 and the trend is the same. %timeit q=['{0}'.format(i) for i in range(100, 100000, 100)] %timeit q=[str(i) for i in range(100, 100000, 100)] %timeit q=['{}'.format(i) for i in range(100, 100000, 100)] 1000 loops, best of 3: 231 µs per loop 1000 loops, best of 3: 298

how does Cpython implement its type Objects, i.e. type's type is always type?

允我心安 提交于 2019-12-03 14:54:06
问题 I understand that everything in python is an Object and that the 'type' (or class) of these object is 'type'. Plus the type of type is also type itself. (as explained nicely here) What I do not understand is how is this circular reference implemented? So i looked here. To quote the portion which might explain what I am looking for: PyTypeObject* PyObject.ob_type This is the type’s type, in other words its metatype. It is initialized by the argument to the PyObject_HEAD_INIT macro, and its

Python string concatenation internal details

五迷三道 提交于 2019-12-03 14:20:11
Assume that we have a list of strings and we want to create a string by concatenating all element in this list. Something like this: def foo(str_lst): result = '' for element in str_lst: result += element return result Since strings are immutable objects, I expect that python creates a new str object and copy contents of result and element at each iteration. It makes O(M * N^2) time complexity, M is the length of each element and N is the size of the list. However, my experiment shows that it runs in linear time. N = 1000000 # 1 million str_lst = ['a' for _ in range(N)] foo(str_lst) # It takes

Where does Python store the name binding of function closure?

天涯浪子 提交于 2019-12-03 13:26:52
So recently I understand the concept of function closure. def outer(): somevar = [] assert "somevar" in locals() and not "somevar" in globals() def inner(): assert "somevar" in locals() and not "somevar" in globals() somevar.append(5) return somevar return inner function = outer() somevar_returned = function() assert id(somevar_returned) == id(function.func_closure[0].cell_contents) As much as I understand, the objective of function closure is to keep an active reference to the object, in order to avoid garbage collection of this object. This is why the following works fine : del outer somevar

Different behavior in python script and python idle?

佐手、 提交于 2019-12-03 11:19:12
In the python idle: >>> a=1.1 >>> b=1.1 >>> a is b False But when I put the code in a script and run it, I will get a different result: $cat t.py a=1.1 b=1.1 print a is b $python t.py True Why did this happen? I know that is compares the id of two objects, so why the ids of two objects are same/unique in python script/idle? I also found that, if I use a small int, for example 1 , instead of 1.1 , the result will be the same in both the python script and python idle. Why did small int and small float have different behavior? I am using CPython 2.7.5. poke When Python executes a script file, the

What are some strategies to write python code that works in CPython, Jython and IronPython

一曲冷凌霜 提交于 2019-12-03 07:12:19
问题 Having tries to target two of these environments at the same time I can safely say the if you have to use a database etc. you end up having to write unique code for that environment. Have you got a great way to handle this situation? 回答1: If you do find you need to write unique code for an environment, use pythons import mymodule_jython as mymodule import mymodule_cpython as mymodule have this stuff in a simple module (''module_importer''?) and write your code like this: from module_importer

How does Python's Garbage Collector Detect Circular References?

爷,独闯天下 提交于 2019-12-03 06:23:09
问题 I'm trying to understand how Python's garbage collector detects circular references. When I look at the documentation, all I see is a statement that circular references are detected, except when the objects involved have a __del__ method. If this happens, my understanding (possibly faulty) is that the gc module acts as a failsafe by (I assume) walking through all the allocated memory and freeing any unreachable blocks. How does Python detect & free circular memory references before making use

'{0}'.format() is faster than str() and '{}'.format() using IPython %timeit and otherwise using pure Python

╄→гoц情女王★ 提交于 2019-12-03 05:28:06
So it's a CPython thing, not quite sure that it has same behaviour with other implementations. But '{0}'.format() is faster than str() and '{}'.format() . I'm posting results from Python 3.5.2 , but, I tried it with Python 2.7.12 and the trend is the same. %timeit q=['{0}'.format(i) for i in range(100, 100000, 100)] %timeit q=[str(i) for i in range(100, 100000, 100)] %timeit q=['{}'.format(i) for i in range(100, 100000, 100)] 1000 loops, best of 3: 231 µs per loop 1000 loops, best of 3: 298 µs per loop 1000 loops, best of 3: 434 µs per loop From the docs on object.__str__(self) Called by str