python-internals

Why is this loop faster than a dictionary comprehension for creating a dictionary?

谁说胖子不能爱 提交于 2019-12-04 14:59:22
问题 I don't come from a software/computer science background but I love to code in Python and can generally understand why things are faster. I am really curious to know why this for loop runs faster than the dictionary comprehension. Any insights? Problem : Given a dictionary a with these keys and values, return a dictionary with the values as keys and the keys as values. (challenge: do this in one line) and the code a = {'a':'hi','b':'hey','c':'yo'} b = {} for i,j in a.items(): b[j]=i %% timeit

Can __setattr__() can be defined in a class with __slots__?

我是研究僧i 提交于 2019-12-04 11:27:17
问题 Say I have a class which defines __slots__ : class Foo(object): __slots__ = ['x'] def __init__(self, x=1): self.x = x # will the following work? def __setattr__(self, key, value): if key == 'x': object.__setattr__(self, name, -value) # Haha - let's set to minus x Can I define __setattr__() for it? Since Foo has no __dict__ , what will it update? 回答1: All your code does, apart from negate the value, is call the parent class __setattr__ , which is exactly what would happen without your _

Fatal Python error and `BufferedWriter`

社会主义新天地 提交于 2019-12-04 09:10:30
问题 I've came across this paragraph in the Documentations which says: Binary buffered objects (instances of BufferedReader , BufferedWriter , BufferedRandom and BufferedRWPair ) protect their internal structures using a lock; it is therefore safe to call them from multiple threads at once. I'm not sure why they need to "protect" their internal structures given the GIL is in action. Who cares? I didn't care much until I found out that this lock has some significance, consider this piece of code:

Python dictionary iterator performance

帅比萌擦擦* 提交于 2019-12-04 03:15:43
问题 When working with dictionaries in Python, this page says that the time complexity of iterating through the element of the dictionary is O(n) , where n is the largest size the dictionary has been. However, I don't think that there is an obvious way to iterate through the elements of a hash table. Can I assume good performance of dict.iteritems() when iterating through element of a hash table, without too much overhead? Since dictionaries are used a lot in Python, I assume that this is

range non-default parameter follows default one

岁酱吖の 提交于 2019-12-04 00:33:01
问题 Why does range allow a non-default parameter ( stop ) to follow a default parameter ( start )? Case in point: >>> r = range(1, 2, 3) >>> print(r.start, r.stop, r.step) 1 2 3 >>> r = range(10) >>> print(r.start, r.stop, r.step) 0 10 1 Trying to emulate the signature is an obvious violation: def my_range(start=0, stop, end=1): pass I understand that the fact it is implemented in C probably allows for behavior that would be a violation in Pythonland. I'm guessing this was done to make the API

Internals for python tuples

◇◆丶佛笑我妖孽 提交于 2019-12-04 00:16:32
问题 >>> a=1 >>> b=1 >>> id(a) 140472563599848 >>> id(b) 140472563599848 >>> x=() >>> y=() >>> id(x) 4298207312 >>> id(y) 4298207312 >>> x1=(1) >>> x2=(1) >>> id(x1) 140472563599848 >>> id(x2) 140472563599848 until this point I was thinking there will be only one copy of immutable object and that will be shared(pointed) by all the variables. But when I tried, the below steps I understood that I was wrong. >>> x1=(1,5) >>> y1=(1,5) >>> id(x1) 4299267248 >>> id(y1) 4299267320 can anyone please

Why are assignments not allowed in Python's `lambda` expressions?

戏子无情 提交于 2019-12-03 23:48:46
问题 This is not a duplicate of Assignment inside lambda expression in Python, i.e., I'm not asking how to trick Python into assigning in a lambda expression. I have some λ-calculus background. Considering the following code, it looks like Python is quite willing to perform side-effects in lambda expressions: #!/usr/bin/python def applyTo42(f): return f(42) def double(x): return x * 2 class ContainsVal: def __init__(self, v): self.v = v def store(self, v): self.v = v def main(): print('==

How does Python bypass normal attribute lookup to find `__dict__`?

别来无恙 提交于 2019-12-03 21:59:38
I understand that __dict__ in obj.__dict__ is a descriptor attribute of type(obj) , so the lookup for obj.__dict__ is type(obj).__dict__['__dict__'].__get__(obj) . From https://stackoverflow.com/a/46576009 It's tempting to say that __dict__ has to be a descriptor because implementing it as a __dict__ entry would require you to find the __dict__ before you can find the __dict__ , but Python already bypasses normal attribute lookup to find __dict__ when looking up other attributes , so that's not quite as compelling as it initially sounds. If the descriptors were replaced with a '__dict__' key

Where is Python's shutdown procedure documented?

旧时模样 提交于 2019-12-03 19:11:01
问题 CPython has a strange behaviour where it sets modules to None during shutdown. This screws up error logging during shutdown of some multithreading code I've written. I can't find any documentation of this behaviour. It's mentioned in passing in PEP 432: [...] significantly reducing the number of modules that will experience the "module globals set to None" behaviour that is used to deliberate break cycles and attempt to releases more external resources cleanly. There are SO questions about

Why were literal formatted strings (f-strings) so slow in Python 3.6 alpha? (now fixed in 3.6 stable)

╄→尐↘猪︶ㄣ 提交于 2019-12-03 18:46:29
问题 I've downloaded a Python 3.6 alpha build from the Python Github repository, and one of my favourite new features is literal string formatting. It can be used like so: >>> x = 2 >>> f"x is {x}" "x is 2" This appears to do the same thing as using the format function on a str instance. However, one thing that I've noticed is that this literal string formatting is actually very slow compared to just calling format . Here's what timeit says about each method: >>> x = 2 >>> timeit.timeit(lambda: f