标签: python-internals

python对象如何存储垃圾收集的引用计数器

我试图找出python如何存储对象的引用计数:

getrefcount(...)
    getrefcount(object) -> integer

    Return the reference count of object.  The count returned is generally
    one higher than you might expect, because it includes the (temporary)
    reference as an argument to getrefcount().
    >>>

>>> s = 'string'
>>> sys.getrefcount(s)
28
>>> d = {'key' : s}
>>> sys.getrefcount(s)
29
>>> l = [s]
>>> sys.getrefcount(s)
30
>>> del l
>>> sys.getrefcount(s)
29
>>> del d
>>> sys.getrefcount(s)
28
>>>
Run Code Online (Sandbox Code Playgroud)

在我上面的代码片段中,一旦我创建了一个字符串对象,s我得到了ref-count 28,然后当我在字典中分配它的ref-count增加1.我不知道为什么它从28开始.

所以,在这里我试图找出这个值存储的位置或python如何获取它.

谢谢

python garbage-collection python-internals

5
推荐指数
1
解决办法
271
查看次数

为什么在Python函数中可以使用超过2 ^ 16个常量?

在像peephole这样的内部模块中,参数LOAD_CONST存储在后面的两个字节中opcode.

例如,它用于获取操作参数的宏实现为:

#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))

参数LOAD_CONST是consts数组的索引.

所以我猜我们在Python函数中最多只能使用2 ^ 16个常量.

但是当我尝试使用66666(> 65536)常量的函数时,它仍然可以正常运行.

可能是什么原因?

python python-internals

5
推荐指数
1
解决办法
150
查看次数

为什么six.py使用自定义类来查找MAXSIZE?

我正在浏览six.pydjango utils中的代码,对于非Jython实现,尝试为int找到MAXSIZE.现在,这样做的方式很有趣 - 不是在语句本身上捕获异常,而是将语句包装在__len__自定义类中的方法中.这样做的原因是什么?

class X(object):
    def __len__(self):
        return 1 << 31
try:
    len(X())
except OverflowError:
    # 32-bit
    MAXSIZE = int((1 << 31) - 1)
else:
    # 64-bit
    MAXSIZE = int((1 << 63) - 1)
del X
Run Code Online (Sandbox Code Playgroud)

如果我没有错,同样可以缩短到下面,对吧?

try:
    1 << 31
except OverflowError:
    # 32-bit
    MAXSIZE = int((1 << 31) - 1)
else:
    # 64-bit
    MAXSIZE = int((1 << 63) - 1)
Run Code Online (Sandbox Code Playgroud)

python python-2.x python-3.x python-internals six

5
推荐指数
1
解决办法
62
查看次数

在__init__中更改类属性

我正在查看Stack Overflow问题计算类的实例?,我不确定为什么该解决方案有效,而使用简单添加的解决方案则不然.我想这更像是一个关于如何存储和访问类与实例变量的问题.

这是我认为应该起作用的代码,但代之以4为id:

class foo():
      num = 3    # trying 3 instead of 0 or 1 to make sure the add is working

      def __init__(self):
        self.num += 1
        self.id = self.num

f = foo()
g = foo()

print f.id    # 4
print g.id    # 4
Run Code Online (Sandbox Code Playgroud)

该self.num +=1声明有些工作(增加正在发生,但不是作业).

正在进行这项任务的情况下发生的事情在这里失败,而itertools.count任务在另一个问题的解决方案中成功了吗?

python python-2.7 python-internals

5
推荐指数
2
解决办法
1580
查看次数

关于__class__的闭包

我最近逐步完成了CPython源代码,特别是在编译期间查看类的符号表条目.

我碰到了typedef struct _symtable_entry结构的以下条目:

[-- other entries --]
unsigned ste_needs_class_closure : 1; /* for class scopes, true if a
                                         closure over __class__
                                         should be created */
[-- other entries --]
Run Code Online (Sandbox Code Playgroud)

我似乎无法理解它,也无法找到实际设置的python代码示例ste_needs_class_closure == 1.在其他失败的尝试中,我尝试了以下方法:

class foo:
    y = 30
    def __init__(self):
        self.x = 50
    def foobar(self):
        def barfoo():
            print(self.x)
            print(y)
        return barfoo
Run Code Online (Sandbox Code Playgroud)

但即使它执行,执行ste_needs_class_closure期间的价值0也不1是我希望的那样.

实际上改变这个值的功能对它drop_class_free没有多大帮助.不幸的是,它也没有任何赞美它的评论.

它实际上用于analyze_block评论:

/* Check if any local variables must be converted to …
Run Code Online (Sandbox Code Playgroud)

python closures python-3.x python-internals

5
推荐指数
1
解决办法
76
查看次数

将Python嵌入C:链接错误-对PyString_AsString的未定义引用

我试图将python程序嵌入C程序中。我的操作系统是Ubuntu 14.04

我尝试将python 2.7和python 3.4解释器嵌入到同一C代码库中(作为单独的应用程序)。嵌入python 2.7时,编译和链接有效,但不嵌入python 3.4。在链接器阶段失败。

这是我的C代码(只是一个示例,不是真实代码)

简单的

#include <stdio.h>
#include <Python.h>

int main(int argc, char *argv[])
{
    PyObject *pName, *pModule, *pFunc, *pValue;
    char module[] = "get_version";
    char func[] = "get_version";
    char module_path[] = ".";

    Py_Initialize();
    PyObject *sys_path = PySys_GetObject("path");
    PyList_Append(sys_path, PyUnicode_FromString(module_path));

    pName = PyUnicode_FromString(module);
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);

    if(pModule != NULL)
    {
        pFunc = PyObject_GetAttrString(pModule, func);
        if (pFunc && PyCallable_Check(pFunc))
        {
            pValue = PyObject_CallObject(pFunc, NULL);
            if (pValue != NULL) {
                printf("Python version: %s\n", PyString_AsString(pValue));
                Py_DECREF(pValue);
            }
            else { …
Run Code Online (Sandbox Code Playgroud)

c python python-embedding python-3.x python-internals

5
推荐指数
1
解决办法
3322
查看次数

"del sys.modules [module]"实际上做了什么?

众所周知,您可以del sys.modules[module]删除导入的模块.所以我在想:这与重写有sys.modules什么不同?一个有趣的事实是,重写sys.modules不能真正删除模块.

# a_module.py
print("a module imported")
Run Code Online (Sandbox Code Playgroud)

然后

import sys

def func1():
    import a_module
    # del sys.modules['a_module']
    sys.modules = {
        k: v for k, v in sys.modules.items() if 'a_module' not in k}
    print('a_module' not in sys.modules)  # True

def func2():
    import a_module

func1()  # a module imported
func2()  # no output here
Run Code Online (Sandbox Code Playgroud)

如果我使用del sys.modules['a_module'],调用func2()也打印a module imported,这意味着a_module成功删除.

我的问题是:del sys.modules[module]除了更改字典之外,实际上做了什么?

python module sys python-internals

5
推荐指数
1
解决办法
2301
查看次数

如何从键/初始计数对列表中初始化计数器?

如果我有一(key, value)对配对,我可以快速初始化这样的字典:

>>> data = [ ('a', 1), ('b', 2) ]
>>> dict(data) 
{'a': 1, 'b': 2} 
Run Code Online (Sandbox Code Playgroud)

我想用Counter字典做同样的事; 但怎么样?构造函数和update()方法都将有序对视为键,而不是键值对:

>>> from collections import Counter
>>> Counter(data)
Counter({('a', 1): 1, ('b', 2): 1})
Run Code Online (Sandbox Code Playgroud)

我能管理的最好的就是使用一个临时字典,这个字典很丑陋而且不必要地迂回:

>>> Counter(dict(data))
Counter({'b': 2, 'a': 1})
Run Code Online (Sandbox Code Playgroud)

有没有一种正确的方法Counter从一(key, count)对配对中直接初始化?我的用例涉及从文件中读取大量已保存的计数(使用唯一键).

python counter data-structures python-3.x python-internals

5
推荐指数
1
解决办法
3062
查看次数

python字节码中的load name和load global有什么区别?

加载名称接受其参数,并将存储名称存储的名称值推入参数指示的位置。load global的功能类似,但是字节码中似乎没有全局存储。那么有什么区别以及如何加载全局工作

python bytecode python-internals

5
推荐指数
2
解决办法
397
查看次数

向扩展方法添加带注释的签名

将Python嵌入应用程序中并编写扩展类型时,可以signature使用适当制作的.tp_doc字符串将a添加到方法中。

static PyMethodDef Answer_methods[] = {
  { "ultimate", (PyCFunction)Answer_ultimate, METH_VARARGS, 
    "ultimate(self, question='Life, the universe, everything!')\n"
    "--\n"
    "\n"
    "Return the ultimate answer to the given question." },
  { NULL }
};
Run Code Online (Sandbox Code Playgroud)

当help(Answer)执行时,返回(缩写)以下内容:

class Answer(builtins.object)
 |
 |  ultimate(self, question='Life, the universe, everything!')
 |      Return the ultimate answer to the given question.
Run Code Online (Sandbox Code Playgroud)

很好,但是我使用的是Python3.6,它支持注释。我想将问题注释为字符串,并返回一个int函数。我试过了:

static PyMethodDef Answer_methods[] = {
  { "ultimate", (PyCFunction)Answer_is_ultimate, METH_VARARGS, 
    "ultimate(self, question:str='Life, the universe, everything!') -> int\n"
    "--\n"
    "\n"
    "Return the ultimate answer to the …
Run Code Online (Sandbox Code Playgroud)

python signature python-c-api python-internals python-3.6

5
推荐指数
1
解决办法
299
查看次数