python-internals

Why is one class variable not defined in list comprehension but another is?

◇◆丶佛笑我妖孽 提交于 2019-11-26 07:48:08
问题 I just read the answer to this question: Accessing class variables from a list comprehension in the class definition It helps me to understand why the following code results in NameError: name \'x\' is not defined : class A: x = 1 data = [0, 1, 2, 3] new_data = [i + x for i in data] print(new_data) The NameError occurs because x is not defined in the special scope for list comprehension. But I am unable to understand why the following code works without any error. class A: x = 1 data = [0, 1,

Python string with space and without space at the end and immutability

偶尔善良 提交于 2019-11-26 06:48:00
问题 I learnt that in some immutable classes, __new__ may return an existing instance - this is what the int , str and tuple types sometimes do for small values. But why do the following two snippets differ in the behavior? With a space at the end: >>> a = \'string \' >>> b = \'string \' >>> a is b False Without a space: >>> c = \'string\' >>> d = \'string\' >>> c is d True Why does the space bring the difference? 回答1: This is a quirk of how the CPython implementation chooses to cache string

What exactly is contained within a obj.__closure__?

≯℡__Kan透↙ 提交于 2019-11-26 06:29:19
问题 Beazley pg 100 mentions: >>>python.__closure__ (<cell at 0x67f50: str object at 0x69230>,) >>>python.__closure__[0].cell_contents my understanding is that __closure__ is a list but what\'s all this cell stuff and str object?? That looks like a 1-ary tuple? 回答1: Closure cells refer to values needed by the function but are taken from the surrounding scope. When Python compiles a nested function, it notes any variables that it references but are only defined in a parent function (not globals) in

Why does a class&#39; body get executed at definition time?

我是研究僧i 提交于 2019-11-26 05:37:49
问题 In contrast to functions, a class\' body is executed at definition time: class A(object): print \'hello\' Out: hello Why is it the case? Is it related to @classmethod / @staticmethod methods and class attributes? 回答1: Everything is executed at the module level when Python first imports a module. Function bodies (and generator expression bodies) are the exception here, not the rule. Python executes everything to create the objects contained in a module; like everything in Python, classes are

How to override the copy/deepcopy operations for a Python object?

天大地大妈咪最大 提交于 2019-11-26 05:22:02
问题 I understand the difference between copy vs. deepcopy in the copy module. I\'ve used copy.copy and copy.deepcopy before successfully, but this is the first time I\'ve actually gone about overloading the __copy__ and __deepcopy__ methods. I\'ve already Googled around and looked through the built-in Python modules to look for instances of the __copy__ and __deepcopy__ functions (e.g. sets.py , decimal.py , and fractions.py ), but I\'m still not 100% sure I\'ve got it right. Here\'s my scenario:

list() uses slightly more memory than list comprehension

送分小仙女□ 提交于 2019-11-26 04:43:08
问题 So i was playing with list objects and found little strange thing that if list is created with list() it uses more memory, than list comprehension? I\'m using Python 3.5.2 In [1]: import sys In [2]: a = list(range(100)) In [3]: sys.getsizeof(a) Out[3]: 1008 In [4]: b = [i for i in range(100)] In [5]: sys.getsizeof(b) Out[5]: 912 In [6]: type(a) == type(b) Out[6]: True In [7]: a == b Out[7]: True In [8]: sys.getsizeof(list(b)) Out[8]: 1008 From the docs: Lists may be constructed in several

time.sleep — sleeps thread or process?

安稳与你 提交于 2019-11-26 04:32:21
问题 In Python for *nix, does time.sleep() block the thread or the process? 回答1: It blocks the thread. If you look in Modules/timemodule.c in the Python source, you'll see that in the call to floatsleep() , the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps. You can also test this with a simple python program: import time from threading import Thread class

Two variables in Python have same id, but not lists or tuples

馋奶兔 提交于 2019-11-26 04:21:22
问题 Two variables in Python have the same id : a = 10 b = 10 a is b >>> True If I take two list s: a = [1, 2, 3] b = [1, 2, 3] a is b >>> False according to this link Senderle answered that immutable object references have the same id and mutable objects like lists have different ids. So now according to his answer, tuples should have the same ids - meaning: a = (1, 2, 3) b = (1, 2, 3) a is b >>> False Ideally, as tuples are not mutable, it should return True , but it is returning False ! What is

Why does id({}) == id({}) and id([]) == id([]) in CPython?

醉酒当歌 提交于 2019-11-26 01:23:22
问题 Why does CPython (no clue about other Python implementations) have the following behavior? tuple1 = () tuple2 = () dict1 = {} dict2 = {} list1 = [] list2 = [] # makes sense, tuples are immutable assert(id(tuple1) == id(tuple2)) # also makes sense dicts are mutable assert(id(dict1) != id(dict2)) # lists are mutable too assert(id(list1) != id(list2)) assert(id(()) == id(())) # why no assertion error on this? assert(id({}) == id({})) # or this? assert(id([]) == id([])) I have a few ideas why it

How does the @property decorator work?

为君一笑 提交于 2019-11-26 01:18:09
问题 I would like to understand how the built-in function property works. What confuses me is that property can also be used as a decorator, but it only takes arguments when used as a built-in function and not when used as a decorator. This example is from the documentation: class C(object): def __init__(self): self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, \"I\'m the \'x\' property.\") property \'s