itertools.accumulate() versus functools.reduce()

It seems that accumulate keeps the previous results, whereas reduce (which is known as fold in other languages) does not necessarily. e.g. list(accumulate([1,2,3], operator.add)) would return [1,3,6] whereas a plain fold would return 6 Also (just for fun, don’t do this) you can define accumulate in terms of reduce def accumulate(xs, f): return reduce(lambda a, … Read more

Non-blocking multiprocessing.connection.Listener?

One solution that I found (although it might not be the most “elegant” solution is using conn.poll. (documentation) Poll returns True if the Listener has new data, and (most importantly) is nonblocking if no argument is passed to it. I’m not 100% sure that this is the best way to do this, but I’ve had … Read more

Getting exception details in Python

You can use sys.exc_info to get information about the exception currently being handled, including the exception object itself. An IOError exception contains all of the information you need, including the filename, the errno, and a string describing the error: import sys try: f1 = open(‘example1’) f2 = open(‘example2’) except IOError: type, value, traceback = sys.exc_info() … Read more

python: Is there a downside to using faulthandler?

This feature is very useful. Is there any particular reason it isn’t enabled by default? Does it have any negative effects on performance? The reason is that faulthandler remembers the file descriptor of stderr, usually fd 2. The problem is that fd 2 may become something else, like a socket, a pipe, an important file, … Read more

Is python package virtualenv necessary when I use python 3.3?

Generally, the virtualenv package is not required when using python3.3 or later, since it was incorporated into the standard library via PEP 405. As you note in the question, there are some relatively small differences between the latest versions of virtualenv and the venv package in the standard library. In part (e.g. –no-site-packages) this stems … Read more

Can’t catch mocked exception because it doesn’t inherit BaseException

I could reproduce the error with a minimal example: foo.py: class MyError(Exception): pass class A: def inner(self): err = MyError(“FOO”) print(type(err)) raise err def outer(self): try: self.inner() except MyError as err: print (“catched “, err) return “OK” Test without mocking : class FooTest(unittest.TestCase): def test_inner(self): a = foo.A() self.assertRaises(foo.MyError, a.inner) def test_outer(self): a = foo.A() … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)