python-internals

Set literal gives different result from set function call

梦想与她 提交于 2019-12-02 19:56:02
Why does the set function call wipe out the dupes, but parsing a set literal does not? >>> x = Decimal('0') >>> y = complex(0,0) >>> set([0, x, y]) {0} >>> {0, x, y} {Decimal('0'), 0j} (Python 2.7.12. Possibly same root cause as for this similar question) Sets test for equality, and until there are new Python releases, the order in which they do this can differ based on the form you hand the values to the set being constructed, as I'll show below. Since 0 == x is true and 0 == y is true, but x == y is false , the behaviour here is really undefined , as the set assumes that x == y must be true

Very strange behavior of operator 'is' with methods

隐身守侯 提交于 2019-12-02 19:52:39
Why is the first result False , should it not be True ? >>> from collections import OrderedDict >>> OrderedDict.__repr__ is OrderedDict.__repr__ False >>> dict.__repr__ is dict.__repr__ True For user-defined functions, in Python 2 unbound and bound methods are created on demand, through the descriptor protocol ; OrderedDict.__repr__ is such a method object, as the wrapped function is implemented as a pure-Python function . The descriptor protocol will call the __get__ method on objects that support it, so __repr__.__get__() is called whenever you try to access OrderedDict.__repr__ ; for

safe usage of remove method in python

醉酒当歌 提交于 2019-12-02 17:26:37
问题 I inherited a UserList class from list and implemented the following method to remove entries which are marked deleted def purge_deleted(self): for element in list.__iter__(self): if ele.mark_deleted < 1: self.remove(element) the element in itself is a complicated entity having methods overriding comparison operators Questions Will the above code successfully work in removing the objects? How does python internally works to remove the elements from the list? Will it not create a problem when

What exactly is __weakref__ in Python?

谁说我不能喝 提交于 2019-12-02 14:16:48
Surprisingly, there's no explicit documentation for __weakref__ . Weak references are explained here . __weakref__ is also shortly mentioned in the documentation of __slots__ . But I could not find anything about __weakref__ itself. What exactly is __weakref__ ? - Is it just a member acting as a flag: If present, the object may be weakly-referenced? - Or is it a function/variable that can be overridden/assigned to get a desired behavior? How? Dunes __weakref__ is just an opaque object that references all the weak references to the current object. In actual fact it's an instance of weakref (or

Why are some float < integer comparisons four times slower than others?

本小妞迷上赌 提交于 2019-12-02 13:50:55
When comparing floats to integers, some pairs of values take much longer to be evaluated than other values of a similar magnitude. For example: >>> import timeit >>> timeit.timeit("562949953420000.7 < 562949953421000") # run 1 million times 0.5387085462592742 But if the float or integer is made smaller or larger by a certain amount, the comparison runs much more quickly: >>> timeit.timeit("562949953420000.7 < 562949953422000") # integer increased by 1000 0.1481498428446173 >>> timeit.timeit("562949953423001.8 < 562949953421000") # float increased by 3001.1 0.1459577925548956 Changing the

safe usage of remove method in python

浪子不回头ぞ 提交于 2019-12-02 10:04:59
I inherited a UserList class from list and implemented the following method to remove entries which are marked deleted def purge_deleted(self): for element in list.__iter__(self): if ele.mark_deleted < 1: self.remove(element) the element in itself is a complicated entity having methods overriding comparison operators Questions Will the above code successfully work in removing the objects? How does python internally works to remove the elements from the list? Will it not create a problem when we simultaneously iterate and modify the same list? You will end up skipping elements, as the iterator

How to get name of function's actual parameters in Python?

余生颓废 提交于 2019-12-02 09:08:07
问题 For example: def func(a): # how to get the name "x" x = 1 func(x) If I use inspect module I can get the stack frame object: import inspect def func(a): print inspect.stack() out: [ (<frame object at 0x7fb973c7a988>, 'ts.py', 9, 'func', [' stack = inspect.stack()\n'], 0) (<frame object at 0x7fb973d74c20>, 'ts.py', 18, '<module>', ['func(x)\n'], 0) ] or use inspect.currentframe() I can get the current frame. But I can only get the name "a" by inspect the function object. Use inspect.stack I can

Is the empty tuple in Python a “constant” [duplicate]

懵懂的女人 提交于 2019-12-02 03:47:50
This question already has an answer here: compare object to empty tuple with the 'is' operator in Python 2.x 4 answers I want to make my code more (memory-)efficient. Right now we have a lot of functions that take an iterable as parameter like: def foo(para,meter,iterable): #... pass and sometimes we have to provide it an empty list to do its work properly: foo(14,25,[]) . The problem is that each time a new list is constructed: it requires to allocate on the heap, and a list seems to 64 bytes of memory (on my own machine, tested with sys.getsizeof([]) ) whereas the empty tuple only takes a

Python - monkey patch fails, why?

微笑、不失礼 提交于 2019-12-01 21:59:08
问题 I want to monkey patch on f(*args, **kwargs) from an installed module. I use the idea of decorator on my own code, but other methods from the installed module fails to call f correctly. Here is an example: import numpy as np def log(func): def wrapper(*args, **kwargs): print('logging') return func(*args, **kwargs) return wrapper if __name__ == "__main__": a1 = np.asarray([0, 1, 2]) print(f'a1={a1}') a2 = np.array([0, 1, 2]) print(f'a2={a2}') np.array = log(np.array) a3 = np.asarray([0, 1, 2])

Python - monkey patch fails, why?

你说的曾经没有我的故事 提交于 2019-12-01 21:12:20
I want to monkey patch on f(*args, **kwargs) from an installed module. I use the idea of decorator on my own code, but other methods from the installed module fails to call f correctly. Here is an example: import numpy as np def log(func): def wrapper(*args, **kwargs): print('logging') return func(*args, **kwargs) return wrapper if __name__ == "__main__": a1 = np.asarray([0, 1, 2]) print(f'a1={a1}') a2 = np.array([0, 1, 2]) print(f'a2={a2}') np.array = log(np.array) a3 = np.asarray([0, 1, 2]) print(f'a3={a3}') a4 = np.array([0, 1, 2]) print(f'a4={a4}') The output is: a1=[0 1 2] a2=[0 1 2] a3=