python-internals

Why is it slower to iterate over a small string than a small list?

℡╲_俬逩灬. 提交于 2019-11-28 13:26:42
问题 I was playing around with timeit and noticed that doing a simple list comprehension over a small string took longer than doing the same operation on a list of small single character strings. Any explanation? It's almost 1.35 times as much time. >>> from timeit import timeit >>> timeit("[x for x in 'abc']") 2.0691067844831528 >>> timeit("[x for x in ['a', 'b', 'c']]") 1.5286479570345861 What's happening on a lower level that's causing this? 回答1: TL;DR The actual speed difference is closer to

why does sys.stdout = None work?

自作多情 提交于 2019-11-28 12:13:39
i can silence and restore sys.stdout this way: import sys sys.stdout = None print('hello') # does not write to stdout sys.stdout = sys.__stdout__ print('hello') # writes to stdout i know i'd better be using contextlib.redirect_stdout which probably does something similar but my question is: why does the above code work? i'd have assumed python would call things like sys.stdout.write() so whatever i replace sys.stdout with should have a write method (like e.g. io.StringIO ) at least. print has an explicit check for None . /* sys.stdout may be None when FILE* stdout isn't connected */ if (file =

What is under the hood of x = 'y' 'z' in Python?

对着背影说爱祢 提交于 2019-11-28 11:52:24
If you run x = 'y' 'z' in Python, you get x set to 'yz' , which means that some kind of string concatenation is occurring when Python sees multiple strings next to each other. But what kind of concatenation is this? Is it actually running 'y' + 'z' or is it running ''.join('y','z') or something else? The Python parser interprets that as one string. This is well documented in the Lexical Analysis documentation : String literal concatenation Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as

Unexpected value from sys.getrefcount

杀马特。学长 韩版系。学妹 提交于 2019-11-28 11:36:30
Under Python 2.7.5 >>> import sys >>> sys.getrefcount(10000) 3 Where are the three refcount? PS: when the 10000 PyIntObject would be Py_DECREF to 0 ref and deallocated? Do not say about gc stuff, reference count itself can work without gc. When you do something in the REPL console, the string will be compiled internally and during the compilation process, Python creates an intermediate list with the list of strings apart from tokens. So, that is reference number 1. You can check this like this import gc print gc.get_referrers(10000) # [['sys', 'dis', 'gc', 'gc', 'get_referrers', 10000], (-1,

Why is a function/method call in python expensive?

对着背影说爱祢 提交于 2019-11-28 11:18:02
In this post , Guido van Rossum says that a function call may be expensive, but I do not understand why nor how much expensive can be. How much delay adds to your code a simple function call and why? A function call requires that the current execution frame is suspended, and a new frame is created and pushed on the stack. This is relatively expensive, compared to many other operations. You can measure the exact time required with the timeit module: >>> import timeit >>> def f(): pass ... >>> timeit.timeit(f) 0.15175890922546387 That's 1/6th of a second for a million calls to an empty function;

How do chained comparisons in Python actually work?

我只是一个虾纸丫 提交于 2019-11-28 11:16:28
The Python Doc for Comparisons says: Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z , except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false). And these SO questions/answers shed some more light on such usage: Python comparison operators chaining/grouping left to right? What does "evaluated only once" mean for chained comparisons in Python? , in particular the currently-accepted answer So something like (contrived example): if 1 < input("Value:") < 10: print "Is greater than 1 and less than

How does __call__ actually work?

 ̄綄美尐妖づ 提交于 2019-11-28 11:11:33
Python's magic method __call__ is called whenever you attempt to call an object. Cls()() is thus equal to Cls.__call__(Cls()) . Functions are first class objects in Python, meaning they're just callable objects (using __call__ ). However, __call__ itself is a function, thus it too has __call__ , which again has its own __call__ , which again has its own __call__ . So Cls.__call__(Cls()) is thus equal to Cls.__call__.__call__(Cls()) and again equilevant to Cls.__call__.__call__.__call__(Cls()) and so on and so forth. How does this infinite loop end? How does __call__ actually execute the code?

Why does + (plus) can concatenate two strings in Python?

半世苍凉 提交于 2019-11-28 10:38:14
I'm learning Learn Python the hard way. w = "This is the left side of..." e = "a string with a right side." print w + e Explain why adding the two strings w and e with + makes a longer string. Even I know it can work, but I don't understand why and how? Please help me. Python uses + to concatenate strings because that's how core developers of Python defined that operator. While it's true that __add__ special method is normally used to implement the + operator, + ( BINARY_ADD bytecode instruction ) does not call str.__add__ because + treats strings specially in both Python 2 and Python 3.

Why is the __dict__ of instances so much smaller in size in Python 3?

半腔热情 提交于 2019-11-28 09:48:58
In Python, dictionaries created for the instances of a class are tiny compared to the dictionaries created containing the same attributes of that class: import sys class Foo(object): def __init__(self, a, b): self.a = a self.b = b f = Foo(20, 30) When using Python 3.5.2, the following calls to getsizeof produce: >>> sys.getsizeof(vars(f)) # vars gets obj.__dict__ 96 >>> sys.getsizeof(dict(vars(f)) 288 288 - 96 = 192 bytes saved! Using Python 2.7.12, though, on the other hand, the same calls return: >>> sys.getsizeof(vars(f)) 280 >>> sys.getsizeof(dict(vars(f))) 280 0 bytes saved. In both cases

what happens when you compare two strings in python

半城伤御伤魂 提交于 2019-11-28 09:35:11
问题 When comparing strings in python e.g. if "Hello" == "Hello": #execute certain code I am curious about what the code is that compares the strings. So if i were to compare these in c i would just compare each character and break when one character doesn't match. i'm wondering exactly what the process is of comparing two strings like this, i.e. when it will break and if there is any difference between this comparison and the method said above other than redundancy in lines of code 回答1: I'm going