Django values_list vs values

The values() method returns a QuerySet containing dictionaries: <QuerySet [{‘comment_id’: 1}, {‘comment_id’: 2}]> The values_list() method returns a QuerySet containing tuples: <QuerySet [(1,), (2,)]> If you are using values_list() with a single field, you can use flat=True to return a QuerySet of single values instead of 1-tuples: <QuerySet [1, 2]>

TypeError: not all arguments converted during string formatting python

You’re mixing different format functions. The old-style % formatting uses % codes for formatting: ‘It will cost $%d dollars.’ % 95 The new-style {} formatting uses {} codes and the .format method ‘It will cost ${0} dollars.’.format(95) Note that with old-style formatting, you have to specify multiple arguments using a tuple: ‘%d days and %d … Read more

Using both Python 2.x and Python 3.x in IPython Notebook

The idea here is to install multiple ipython kernels. Here are instructions for anaconda. If you are not using anaconda, I recently added instructions using pure virtualenvs. Anaconda >= 4.1.0 Since version 4.1.0, anaconda includes a special package nb_conda_kernels that detects conda environments with notebook kernels and automatically registers them. This makes using a new … Read more

multiprocessing vs multithreading vs asyncio in Python 3

TL;DR Making the Right Choice: We have walked through the most popular forms of concurrency. But the question remains – when should choose which one? It really depends on the use cases. From my experience (and reading), I tend to follow this pseudo code: if io_bound: if io_very_slow: print(“Use Asyncio”) else: print(“Use Threads”) else: print(“Multi … Read more

Converting int to bytes in Python 3

From python 3.2 you can do >>> (1024).to_bytes(2, byteorder=”big”) b’\x04\x00′ https://docs.python.org/3/library/stdtypes.html#int.to_bytes def int_to_bytes(x: int) -> bytes: return x.to_bytes((x.bit_length() + 7) // 8, ‘big’) def int_from_bytes(xbytes: bytes) -> int: return int.from_bytes(xbytes, ‘big’) Accordingly, x == int_from_bytes(int_to_bytes(x)). Note that the above encoding works only for unsigned (non-negative) integers. For signed integers, the bit length is a bit … Read more