小编bad*_*zil的帖子

为什么Python集不能理解'+'?

我想知道为什么这是有效的:

set(range(10)) - set(range(5))
Run Code Online (Sandbox Code Playgroud)

但这不是有效的:

set(range(10)) + set(range(5))
Run Code Online (Sandbox Code Playgroud)

是因为'+'可能意味着交叉和联合吗?

python set

80
推荐指数
6
解决办法
1万
查看次数

在Python unittest框架中修改全局变量

我正在使用Python进行一系列单元测试,其中一些测试依赖于配置变量的值.这些变量存储在全局Python配置文件中,并在其他模块中使用.我想为配置变量的不同值编写单元测试,但尚未找到实现此目的的方法.

我没有可能重写我正在测试的方法的签名.

这就是我想要实现的目标:

from my_module import my_function_with_global_var

class TestSomething(self.unittest):

    def test_first_case(self):
         from config import MY_CONFIG_VARIABLE
         MY_CONFIG_VARIABLE = True
         self.assertEqual(my_function_with_global_var(), "First result")

    def test_second_case(self):
         from config import MY_CONFIG_VARIABLE
         MY_CONFIG_VARIABLE = False
         self.assertEqual(my_function_with_global_var(), "Second result")
Run Code Online (Sandbox Code Playgroud)

谢谢.

编辑:使示例代码更明确.

python unit-testing global-variables

38
推荐指数
2
解决办法
4万
查看次数

IPython中%time和%timeit之间的不一致

我遇到了一个我无法解释的奇怪情况.这是我的测试时间生成一大堆元组:

In [1]: def get_list_of_tuples():
   ...:     return [(i,) for i in range(10**6)]
   ...:

In [2]: %time res = get_list_of_tuples()
CPU times: user 0.93 s, sys: 0.08 s, total: 1.01 s
Wall time: 0.98 s

In [3]: %timeit res = get_list_of_tuples()
1 loops, best of 3: 92.1 ms per loop
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这个大型元组列表的生成只需不到一秒钟.timeit报告执行时间约为0.1秒.为什么这两份报告有这么大的差异?

(在IPython 0.11,Python 2.6.5上测试过.)

python ipython timeit

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

如何在Python Git钩子中使用raw_input()?

我正在为Git编写一个预提交钩子,它运行pyflakes并检查修改后的文件中的制表符和尾随空格(Github上的代码).我想通过要求用户确认来覆盖挂钩,如下所示:

answer = raw_input('Commit anyway? [N/y] ')
if answer.strip()[0].lower() == 'y':
    print >> sys.stderr, 'Committing anyway.'
    sys.exit(0)
else:
    print >> sys.stderr, 'Commit aborted.'
    sys.exit(1)
Run Code Online (Sandbox Code Playgroud)

此代码产生错误:

Commit anyway? [N/y] Traceback (most recent call last):
  File ".git/hooks/pre-commit", line 59, in ?
    main()
  File ".git/hooks/pre-commit", line 20, in main
    answer = raw_input('Commit anyway? [N/y] ')
EOFError: EOF when reading a line
Run Code Online (Sandbox Code Playgroud)

甚至可以在Git钩子中使用raw_input()或类似的函数,如果是的话,我做错了什么?

python git githooks

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

带有内存访问密钥的Python字典?

我想创建一个数据结构,其行为类似于字典,其中添加了一项功能,即跟踪哪些键已被"消耗".请注意,我不能只是弹出值,因为它们被重用.

该结构应该支持这三种情况,即在访问时将密钥标记为已消耗:

if key in d:
    ...
d[key]
d.get(key)
Run Code Online (Sandbox Code Playgroud)

这就是我写的:

class DictWithMemory(dict):

    def __init__(self, *args, **kwargs):
        self.memory = set()
        return super(DictWithMemory, self).__init__(*args, **kwargs)

    def __getitem__(self, key):
        self.memory.add(key)
        return super(DictWithMemory, self).__getitem__(key)

    def __contains__(self, key):
        self.memory.add(key)
        return super(DictWithMemory, self).__contains__(key)

    def get(self, key, d=None):
        self.memory.add(key)
        return super(DictWithMemory, self).get(key, d)

    def unused_keys(self):
        """
        Returns the list of unused keys.
        """
        return set(self.keys()).difference(self.memory)
Run Code Online (Sandbox Code Playgroud)

由于我对dict的内部不是很熟悉,有没有更好的方法来实现这个结果?

python dictionary

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