标签: python-internals

为什么类型检查对返回的类型不起作用?

我只是试图测试:

if type(model_lines) == 'str':
    turn into a list using split
Run Code Online (Sandbox Code Playgroud)

基于:

In [196]: type('a')
Out[196]: str
Run Code Online (Sandbox Code Playgroud)

然而,对于 x,一个字符串:

In [193]: if type(x) == 'str':
    print 'string'
   .....:  

In [195]: if type(x) == type('a'):
    print 'string'
   .....:     
string
Run Code Online (Sandbox Code Playgroud)

我很好奇为什么我不能使用这个输出来检查类型,它看起来更清晰,阅读速度更快。类型实际上返回什么不允许通过其返回显示进行检查?

python typechecking python-internals

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

为什么在Python 3.5中调用__getitem__而在Python 2.7中调用?

我有一个字节的子类,提供了一个__getitem__dunder方法.该__getitem__方法始终在Python 3.5中调用,但仅在Python 2.7中调用非切片键.(相反,似乎父项__getitem__已应用于实例.)为什么这样,是否有解决方法?

class A(object):
    def __getitem__(self, key):
        print("in A.__getitem__ with key " + str(key))
        return []

class B(bytes):
    def __getitem__(self, key):
        print("in B.__getitem__ with key " + str(key))
        return []

if __name__ == "__main__":
    import sys
    print(sys.version)

    a = A()
    b = B()

    print("[0]")
    a[0]
    b[0]

    print("[0:1]")
    a[0:1]
    b[0:1]

    print("[:1]")
    a[:1]
    b[:1]
Run Code Online (Sandbox Code Playgroud)

Python 3.5输出

__getitem__始终调用类定义.

(venv) snafu$ python ./x.py
3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609]
[0]
in A.__getitem__ …
Run Code Online (Sandbox Code Playgroud)

python python-2.7 python-3.x python-internals python-3.5

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

如何在覆盖其类上的 __dict__ 属性后访问实例字典?

考虑这个例子,其中__dict__类的所有实例的 都A将指向全局 dict shared

shared = {'a': 1, 'b': 2}

class A(object):
    def __init__(self):
        self.__dict__ = shared
Run Code Online (Sandbox Code Playgroud)

现在让我们测试一些事情:

>>> a = A()
>>> b = A()
>>> a.a, a.b, b.a, b.b
(1, 2, 1, 2)
>>> b.x = 100
>>> shared
{'a': 1, 'x': 100, 'b': 2}
>>> a.x
100
>>> c = A()
>>> c.a, c.b, c.x
(1, 2, 100)
>>> shared['foo'] = 'bar'
>>> a.foo, b.foo, c.foo
('bar', 'bar', 'bar')
>>> a.__dict__, b.__dict__, …
Run Code Online (Sandbox Code Playgroud)

python class python-internals

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

Python3.5和Python3.6的源代码之间有什么区别?

 testing on ../../test/test_patm.py
python: Python/compile.c:4420: int assemble_lnotab(struct assembler *, 
struct instr *): Assertion `d_lineno >= 0' failed.
Aborted
Run Code Online (Sandbox Code Playgroud)

运行我的测试程序时,我收到了上面给出的错误.最后我发现Python3.5和Python3.6的源代码差别很小.只需一行:

Python3.5

static int
assemble_lnotab(struct assembler *a, struct instr *i)
{
  int d_bytecode, d_lineno;
  Py_ssize_t len;
  unsigned char *lnotab;

  d_bytecode = a->a_offset - a->a_lineno_off;
  d_lineno = i->i_lineno - a->a_lineno;

  assert(d_bytecode >= 0);
  assert(d_lineno >= 0);   // the only difference

  if(d_bytecode == 0 && d_lineno == 0)
      return 1;
  ...
Run Code Online (Sandbox Code Playgroud)

Python 3.6

static int
assemble_lnotab(struct assembler *a, struct instr *i)
{
    int d_bytecode, …
Run Code Online (Sandbox Code Playgroud)

c python python-3.x python-internals

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

Python的内置类型.__ init __(name,bases,dct)有什么作用吗?

我已经看到了一些Python元类使用super()调用的示例type.__init__()。这是做什么的?

例:

class Meta(type):
    def __new__(cls, name, bases, dct):
        dct['a']='a'
        cls_obj = super(Meta, cls).__new__(cls, name, bases, dct)
        return cls_obj

    def __init__(cls_obj, name, bases, dct):
        cls_obj.b = 'b'
        dct['c'] = 'c'
        #what does this do
        super(Meta, cls_obj).__init__(name, bases, dct)

class Meta2(Meta):
    def __init__(cls_obj, name, bases, dct):
        cls_obj.b = 'b'

class Klass(metaclass=Meta):
    pass

class Klass2(metaclass=Meta2):
    pass


if __name__ == '__main__':
    print(Klass.a)
    print(Klass.b)
    print(Klass.c)
Run Code Online (Sandbox Code Playgroud)

输出:

a
b
<...my system traceback...>
AttributeError: type object 'Klass' has no attribute 'c'
Run Code Online (Sandbox Code Playgroud)

显然 …

python metaclass python-internals

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

CPython 中变量赋值是如何实现的?

我知道 Python 中的变量实际上只是某些底层对象的引用/指针。由于它们是指针,我猜它们以某种方式“存储”或以其他方式与它们引用的对象的地址相关联。

这样的“地址存储”可能发生在 CPython 实现的较低级别。但我对 C 的了解还不足以从源代码中推断出这一点,我也不知道从源代码中的哪里开始查找。

所以,我的问题是:

在 CPython 的实现中,对象地址如何存储在指向它们的变量中,或者如何与指向它们的变量关联?

c python cpython python-3.x python-internals

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

为什么我的dict查找不比我在Python中的列表查找更快?

我正在将文件的每一行读入列表和字典,

with open("../data/title/pruned2_titleonly.txt", 'rb') as f_titles:
    titles_lst = f_titles.read().split('\n')
assert titles_lst[-1] == ''
titles_lst.pop() # remove the last element, an empty string

titles_dict = {}
with open("../data/title/pruned2_titleonly.txt", 'rb') as f_titles:
    for i,line in enumerate(f_titles):
        titles_dict[i] = line
Run Code Online (Sandbox Code Playgroud)

我正在通过以随机顺序访问list/dict中的每个项目来测试性能:

n = len(titles_lst)
a = np.random.permutation(n)

%%time
for i in xrange(10):
    t = []
    for b in a:
        t.append(titles_lst[b])
    del t

>>> CPU times: user 18.2 s, sys: 60 ms, total: 18.2 s
>>> Wall time: 18.1 s

%%time
for i in …
Run Code Online (Sandbox Code Playgroud)

python dictionary list python-2.7 python-internals

0
推荐指数
2
解决办法
1556
查看次数

内置函数的实现

我试着环顾四周,但我找不到任何关于这个话题的清楚.

是否在每次启动Python时自动导入的模块中实现内置函数?在哪个模块的情况下?

或者内置函数只是Python解释器中的嵌入式函数?

python python-internals

0
推荐指数
1
解决办法
125
查看次数

通过索引删除列表元素比通过值删除它更有效吗?

在python中,假设我们有以下列表: my_list = ['a', 'b', 'c', 'd', ...]

my_list.pop(3)比效率更高my_list.remove('d')吗?

python performance runtime python-internals

0
推荐指数
2
解决办法
2621
查看次数

为什么'20000是20000'会导致True?

is在Python中测试2个引用是否指向同一个对象.-5到256之间的数字在内部缓存,因此:

a = 10
b = 10
a is b # Results in True
Run Code Online (Sandbox Code Playgroud)

这是如何解释的:

20000 is 20000 # Results in True
Run Code Online (Sandbox Code Playgroud)

这两个数字都高于256. 2个整数不应该是2个不同的对象吗?

python int literals python-2.7 python-internals

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