How can I represent an ‘Enum’ in Python?

Enums have been added to Python 3.4 as described in PEP 435. It has also been backported to 3.3, 3.2, 3.1, 2.7, 2.6, 2.5, and 2.4 on pypi. For more advanced Enum techniques try the aenum library (2.7, 3.3+, same author as enum34. Code is not perfectly compatible between py2 and py3, e.g. you’ll need … Read more

What is the difference between rw+ and r+

On Linux at least, there’s no difference as far as I can tell. Here’s a test script and its corresponding OS syscalls (using strace); tested on python 2.7.9. See http://man7.org/linux/man-pages/man2/open.2.html for more details on the file access and creation flags. It’s not accurate to say a file object opened with ‘r+’ cannot be used to truncate a file – … Read more

How to install pip with Python 3?

edit: Manual installation and use of setuptools is not the standard process anymore. If you’re running Python 2.7.9+ or Python 3.4+ Congrats, you should already have pip installed. If you do not, read onward. If you’re running a Unix-like System You can usually install the package for pip through your package manager if your version of Python is older than 2.7.9 or 3.4, … Read more

How to open a file using the open with statement

Python allows putting multiple open() statements in a single with. You comma-separate them. Your code would then be: And no, you don’t gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return … Read more